C# 12 Feature - Default Values for Lambda Parameters

Default values for lambda parameters in C# 12 make lambda expressions more flexible and concise. This feature allows you to specify default values for parameters in lambda expressions, similar to how you would in method definitions. Please find the example below.

 

You can define default values for parameters within a lambda expression.

using System;

 

Func<int, int, int> add = (x, y = 0) => x + y;

Console.WriteLine(add(5));  // Output: 5

Console.WriteLine(add(5, 3));  // Output: 8

The lambda expression (x, y = 0) => x + y sets a default value of 0 for the parameter y. When calling add(5), it uses the default value, resulting in 5. When calling add(5, 3), it uses the provided value 3, resulting in 8.

 

Usage in Collection Methods:

Default parameter values can be especially useful in methods like Select and Where.

using System;

using System.Linq;

 

var numbers = new[] { 1, 2, 3, 4, 5 };

var incremented = numbers.Select((num, increment = 1) => num + increment);

 

foreach (var n in incremented)

{

   Console.WriteLine(n);  // Output: 2, 3, 4, 5, 6

}

In the above example, Select uses a lambda expression with a default increment value of 1, incrementing each number by 1.

 

Please find below the advantages of default values for lambda parameters.

 

Flexibility: Allows for more concise and readable lambda expressions.

 

Consistency: Provides a uniform way to use default values across methods and lambda expressions.

 

Convenience: Reduces the need for overloaded methods or additional logic to handle default values.

 

Default values for lambda parameters in C# 12 can simplify your code, making it cleaner and more efficient.