Expression Bodied Constructors And Finalizers

C# expression body is a single line expression statement. It is used to provide single life definition to the method, constructor or property.

C# expression bodied constructor is a constructor that contains single line expression statement. The body of constructor does not contain anything except a single expression statement.

It is a concise way to perform some single line operations. Let's see an example.

C# Expression Constructors Example

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:

Output

Hello Rahul

C# Expression Bodied Finalizer

Finalizer is a destroyer that is used to perform cleanup related tasks. Body definition of finalizer is a single line expression.

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

    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:

Output

Hello Rahul
Finalizer Executing

Input Required

This code uses input(). Please provide values below: