Lambdas will be getting a small upgrade in C# 9 with two new features. Neither will change the way code is written, but they do clarify the developer’s intent.

Lambda Discard Parameters allow developers to explicitly indicate that some of the parameters are not needed. This prevents erroneous compiler warnings about unused parameters. This can occur in places such as event handlers where one doesn’t need the sender and object parameter.

button1.Click += (s, e) => ShowDialog();

By replacing the parameters as shown below, it makes it clear that the variables are unused.

button1.Click += (_, _) => ShowDialog();

If necessary, types may be used.

var handler = (object _, EventArgs _) => ShowDialog();

The Static Anonymous Functions feature is used to indicate a lambda or anonymous function cannot capture local variables (including parameters). This next example comes from the original proposal.

int y = 10;
someMethod(x => x + y); // captures 'y', causing unintended allocation.

#c# 9 #.net #development #lambdas #csharp #programming-c

C# 9: Minor Improvements for Lambdas
4.60 GEEK