Expression Bodied Constructors And Finalizers - C# Tutorial
C# Course / Version Features / Expression Bodied Constructors And Finalizers

Expression Bodied Constructors And Finalizers

BLUF: Mastering Expression Bodied Constructors And Finalizers is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: Expression Bodied Constructors And Finalizers

C# is a powerful, modern language for enterprise solutions. Discover how Expression Bodied Constructors And Finalizers enhances your development workflow in the guide below.

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

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 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

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience