C# 12 – Default values for parameters in lambda expressions
Starting with C# version 12, you can specify default values for your parameters in lambda expressions. The syntax and the restrictions on the default parameter values are the same as for methods and local functions.
Let’s take an example:
var incrementBy = (int source, int increment = 1) => source + increment;
Code language: C# (cs)
This lambda can now be consumed as follows:
Console.WriteLine(incrementBy(3));
Console.WriteLine(incrementBy(3, 2));
Code language: C# (cs)
params array in lambda expressions
You can also declare lambda expressions with a params array as parameter:
var sum = (params int[] values) =>
{
int sum = 0;
foreach (var value in values)
{
sum += value;
}
return sum;
};
Code language: C# (cs)
And consume them like any other function:
var empty = sum();
Console.WriteLine(empty); // 0
var sequence = new[] { 1, 2, 3, 4, 5 };
var total = sum(sequence);
Console.WriteLine(total); // 15
Code language: C# (cs)
Error CS8652
The feature ‘lambda optional parameters’ is currently in Preview and unsupported. To use Preview features, use the ‘preview’ language version.
Your project needs to be targeting .NET 8 and C# 12 or newer in order to use the lambda optional parameters feature. If you’re not sure how to switch to C# 12 you can check out this article: https://startdebugging.net/2023/06/how-to-switch-to-c-12/
One Comment