📅  最后修改于: 2023-12-03 15:14:27.408000             🧑  作者: Mango
C# 7.0 introduced a new feature called Expression Bodied Constructors and Finalizers. It allows the developer to use lambda expressions or expression-bodied members to define constructors and finalizers. This feature makes the code more concise and easier to read.
Expression Bodied Constructor is a shorthand way to define constructors in a more concise way. By using Expression Bodied Constructors, we can define the constructor body using a lambda expression. Here's an example:
public class MyClass
{
private string _name;
public MyClass(string name) => _name = name;
}
In the above code, MyClass
is a class with one property _name
of string
type. The constructor of MyClass
is defined using an "arrow function" or lambda expression =>
.
Similarly, we can also use Expression Bodied Finalizers in C# 7.0. Expression-bodied finalizers work the same way as expression-bodied functions, but their body is executed when an object is being destroyed. Here's an example:
public class MyClass
{
private string _name;
public MyClass(string name) => _name = name;
~MyClass() => Console.WriteLine("MyClass object destroyed");
}
In the above code, the finalizer is defined using the same lambda expression syntax as the constructor. When an object of MyClass
is destroyed, the finalizer is called and displays a message in the console.
Expression Bodied Constructors and Finalizer are a useful feature introduced in C# 7.0 that allows developers to write concise, readable and maintainable code. Whether you need to define a constructor or finalizer, using expression-bodied members simplifies the code and makes it easier to read.