Default Values for Lambda Expressions in C# 12

Default Values for Lambda Expression is one of the coolest features from C# 12. This feature is similar to default values for regular method parameters, and it allows to create more flexible and concise lambda expressions.

Default Values for Lambda Expressions

Before C#12, we used the local function or the default parameter value attribute to specify the default parameter value for lambda expressions.

var incrementValue = (int source, int increment ) => source + increment;

Console.WriteLine(incrementValue(5, 3)); // 8
Console.WriteLine(incrementValue(5, 2)); // 7

Since C# 12 is in preview, enable it from the project file by adding the LangVersion property, as shown in the below figure.

With C# 12, we can have a default value for lambda expressions just by adding an equal sign and the value you want to assign to the parameter after its declaration.

For example, int increment equals 3 Lambda expression, 3 set as a default value for increment which add with the source parameter when no value is provided. When the lambda expression is called with this, you won’t have to rely on the system’s default parameter value. It makes the code more readable as well.

var incrementValue = (int source, int increment =3) => source + increment;

Console.WriteLine(incrementValue(5)); // 8
Console.WriteLine(incrementValue(5, 2)); // 7

During the first incrementValue call, the increment parameter will take the default value as 3 since it has a value only for the source parameter.

ASP.NET Core 8 Hosting Recommendation


HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.