C# expression body is a concise way to define a method, constructor, or property with a single line expression statement. It offers a streamlined approach for providing a compact definition to these elements.
A C# expression-bodied constructor is a constructor that includes a single-line expression statement. The constructor body solely consists of a single expression statement and nothing else.
It is an efficient method to execute brief operations within a single line of code. Let's explore an illustration.
C# Expression Constructors Example
using System;
namespace CSharpFeatures
{
class Student
{
public string Name { get; set; }
// Expression Constructor
public Student(string name) => Name = name;
}
class ExpressionConstructor
{
public static void Main()
{
Student student = new Student("Rahul");
Console.WriteLine($"Hello {student.Name}");
}
}
}
Output:
Hello Rahul
C# Expression Bodied Finalizer
Finalizer is a utility that is employed to execute tasks associated with cleanup. The concise definition of finalizer is encapsulated within a single line.
While working with finalizer, following are the key points to remember.
- It can destruct only class instance
- A class can have only one finalizer
- It can't be overloaded or inherited
- It invokes automatically
- It does not contain parameters
C# Expression Bodied Finalizer Example
using System;
namespace CSharpFeatures
{
class Student
{
public string Name { get; set; }
// Expression bodied constructor
public Student(string name) => Name = name;
// Expression bodied finalizer
~Student() => Console.WriteLine("Finalizer Executing");
}
class ExpressionConstructor
{
public static void Main()
{
Student student = new Student("Rahul");
Console.WriteLine($"Hello {student.Name}");
}
}
}
Output:
Hello Rahul
Finalizer Executing