Expression-bodied members in C# Introduced in C# 6.0 and expanded in later versions, this feature enhances code readability and reduces boilerplate code. Expression-bodied provides a concise syntax for defining methods, properties, and other member types when they consist of a single expression.
Traditionally, members such as methods, properties, and indexers were defined with a voluble syntax. Expression-bodied members simplify this by allowing you to use the '=>' operator to define the member body as a single expression.
Expression-bodied members can be used in the various member types including:
Expression-Bodied Methods
The code below creates a method that returns the square of a number that can be defined using the expression-bodied syntax:
csharppublic class MathUtilities { public int Square(int x) => x * x; }
The following code is equivalent to the above code:
csharppublic class MathUtilities { public int Square(int x) { return x * x; } }
For properties, we can use expression-bodied members to define read-only properties succinctly:
csharppublic class Circle { private double radius; public Circle(double radius) => this.radius = radius; public double Area => Math.PI * radius * radius; }
In this above example, Area is a read-only property that computes the area of a circle.
We can also use expression-bodied syntax with indexers:
csharppublic class StringCollection { private List<string> items = new List<string>(); public string this[int index] => items[index]; }
We can similarly define constructors and finalizers:
csharppublic class Person { public string Name { get; } public Person(string name) => Name = name; ~Person() => Console.WriteLine($"{Name} is being finalized."); }
While expression-bodied members improve readability for simple expressions, they may not be suitable for complex logic. In such a scenario, traditional method definitions may be more appropriate.
In Summary, expression-bodied members in C# are a powerful tool for increasing code readability and reducing boilerplate. They are especially useful for describing simple methods and objects. As we become more familiar with this syntax, it becomes useful to write code that is clean and manageable.
Copyrights © 2024 letsupdateskills All rights reserved