Concise Property Definitions in C# with Expression-Bodied Getters and Setters
Learn how to write cleaner and more efficient C# code using expression-bodied getters and setters. This tutorial explains the syntax, demonstrates its use in defining properties with simple logic, and highlights its benefits in improving code readability and maintainability.
Using Expression-Bodied Getters and Setters in C#
What are Expression-Bodied Getters and Setters?
Expression-bodied members (including getters and setters) are a concise syntax feature in C# that allows you to define a method, constructor, or property's body using a single expression. This makes your code cleaner, easier to read, and more maintainable, particularly for simple getters and setters that don't require complex logic.
Syntax of Expression-Bodied Getters and Setters
For simple getters and setters, you can replace the standard getter and setter blocks with a single expression:
Example C# Code
public string Name {
get => _name; // Getter expression body
set => _name = value; // Setter expression body
}
Here, the getter simply returns the value of the private field `_name`. The setter assigns the provided value to the private field `_name`. This is a much more compact way to define a property.
Example: Expression-Bodied Members
This example demonstrates the use of expression-bodied getters and setters in a `Student` class. The constructor also uses an expression body.
C# Code
using System;
public class Student {
private string _name;
public Student(string name) => _name = name; //Expression-bodied constructor
public string Name { get => _name; set => _name = value; }
}
public class Example {
public static void Main(string[] args) {
Student student = new Student("Peter");
Console.WriteLine(student.Name); // Output: Peter
}
}
Conclusion
Expression-bodied members, including getters and setters, are a valuable addition to C#, enhancing code readability and reducing verbosity, particularly for simple properties. This feature promotes cleaner code and simplifies maintenance without sacrificing functionality.