Expression-Bodied Members in C#: Concise and Efficient Method and Property Definitions
Learn how to use expression-bodied members in C# for creating concise and readable methods and properties. This tutorial explains their syntax, demonstrates their use with examples, and highlights their benefits in improving code efficiency and maintainability.
Expression-Bodied Members in C#
Introduction
C# allows you to define methods and properties using a concise syntax called expression-bodied members. This improves code readability and can make your code more efficient.
Expression-Bodied Method Syntax
An expression-bodied method is defined using a lambda expression-like syntax:
Expression-Bodied Method Syntax
access_modifier return_type MethodName(parameters) => expression;
The expression must return a value of the same type as the method's return type (unless the return type is `void`).
Example: Expression-Bodied Method
Expression-Bodied Method Example
using System;
namespace CSharpFeatures {
public class Student {
private string Name { get; set; }
public void ShowName() => Console.WriteLine(Name); //Expression-bodied method
public static void Main(string[] args) {
Student student = new Student();
student.Name = "Peter John";
student.ShowName(); // Output: Peter John
}
}
}
Expression-Bodied Get Property Syntax
Similarly, you can use expression bodies for get-only properties:
Expression-Bodied Get Property Syntax
access_modifier return_type PropertyName { get => expression; }
The expression provides the value for the property. No `return` statement is needed.
Example: Expression-Bodied Get Property
Expression-Bodied Get Property Example
using System;
namespace CSharpFeatures {
public class ExpressionGet {
private static string Name { get => "tutorialsarena"; } //Expression-bodied get property
public static void Main(string[] args) {
Console.WriteLine(ExpressionGet.Name); // Output: tutorialsarena
}
}
}
Conclusion
Expression-bodied members enhance C# code readability and conciseness, especially for simple methods and get-only properties. This feature improves code maintainability and can lead to slightly more efficient code.