In C#12, you can now define default values for parameters on lambda expressions. The syntax and rules are the same as adding default values for arguments to any method or local function.For example:
var addWithDefault = (int addTo = 2) => addTo + 1; addWithDefault(); // 3 addWithDefault(5); // 6
Prior to C# 12 you needed to use a local function or the unwieldy DefaultParameterValue from the System.Runtime.InteropServices namespace to provide a default value for lambda expression parameters.
These approaches still work but are harder to read and are inconsistent with default values on methods. With the new default values on lambdas you’ll have a consistent look for default parameter values on methods, constructors and lambda expressions.
Example
Console.WriteLine("Example - Default values for lambda expressions"); var addWithDefault = (int addDefaultValue = 2) => addDefaultValue + 1; Console.WriteLine("Output->" + addWithDefault()); // Output ->3 Console.WriteLine("Output->" + addWithDefault(5));// Output ->6 Console.ReadKey();
Output
Find out more in the What is new in C#12.
Find out more about lamda expression.
No comments:
Post a Comment