Concise C# Constructors and Finalizers: Using Expression-Bodied Syntax
Learn how to write concise and readable constructors and finalizers in C# using expression-bodied syntax. This tutorial demonstrates the `=>` operator for creating streamlined constructors and finalizers, improving code clarity and maintainability, especially for simple initialization and cleanup tasks.
Expression-Bodied Constructors and Finalizers in C#
C# allows you to define constructors and finalizers using a concise expression-bodied syntax. This can make your code more readable and easier to maintain, especially for simple constructors and finalizers.
Expression-Bodied Constructors
An expression-bodied constructor is a constructor with a single-line body. It's useful for simple constructors that only need to initialize fields. It uses the `=>` operator to define the constructor's body.
public class MyClass {
public string Name { get; set; }
public MyClass(string name) => Name = name; // Expression-bodied constructor
}
Example: Expression-Bodied Constructor
using System;
public class Student {
public string Name { get; set; }
public Student(string name) => Name = name;
}
public class Example {
public static void Main(string[] args) {
Student student = new Student("Alice");
Console.WriteLine(student.Name); // Output: Alice
}
}
Expression-Bodied Finalizers
A finalizer (destructor) performs cleanup operations when an object is garbage collected. You can also define finalizers using an expression body.
Important Considerations for Finalizers
- They only destruct class instances.
- A class can have only one finalizer.
- Finalizers cannot be overloaded or inherited.
- They are invoked automatically by the garbage collector.
- They don't take parameters.
Example: Expression-Bodied Finalizer
public class MyClass {
~MyClass() => Console.WriteLine("Finalizer called!");
}