In-depth understanding of the Lambda operator in C#
The Lambda operator ("=>") in C# is a powerful syntactic sugar that simplifies the creation of anonymous delegates and expression bodies.
Lambda expression
Lambda expressions provide a cleaner alternative to anonymous methods without explicitly declaring a delegate. They are typically used as Lambda parameters of delegate types, such as Func<T, TResult>
or Action<T>
.
For example, create a delegate that returns a person’s name:
Traditional commission writing method:
<code class="language-csharp">Func<Person, string> nameProjection = delegate (Person p) { return p.Name; };</code>
Simplified using Lambda syntax:
<code class="language-csharp">Func<Person, string> nameProjection = p => p.Name;</code>
Expression body members
Starting in C# 6, Lambda syntax is extended to support expression body members for properties and methods. This allows the implementation of a property or method to be defined using simplified expressions without using traditional code blocks.
For example, define a IsValid
attribute to check whether the person's name is not empty and the ID is not -1:
<code class="language-csharp">public int IsValid => name != null && id != -1;</code>
Similarly, the GetHashCode
method can be implemented using Lambda syntax:
<code class="language-csharp">public int GetHashCode() => id.GetHashCode();</code>
More learning resources
Deep Learning:
The above is the detailed content of How Can C#'s Lambda Operator Simplify Delegate Creation and Expression-Bodied Members?. For more information, please follow other related articles on the PHP Chinese website!