Default Values for Lambda Expressions in C# 12

Introduction

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. 

Default Values for Lambda Expressions in C#

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.

Summary

We have seen what is the default value for lambda expressions and how to use it with an example. We will see more on the C# 12 features in my next blog.