Default Values for Lambda Expressions in C# 12
Microsoft has introduced a new feature in C# 12 that promises to enhance the versatility of lambda expressions: default values for lambda expression parameters. This feature aims to create a more seamless programming experience, aligning the use of lambda expressions with the established syntax for default values on methods.
Background: Lambda Expressions
Lambda expressions have always been a cornerstone of C# ever since their introduction, allowing developers to write concise, anonymous functions directly within the code. They have been especially useful in writing LINQ queries and event handlers, among other things.
However, up until C# 11, if a developer wanted to provide default values for parameters in lambda expressions, they had to resort to using local functions or the somewhat convoluted DefaultParameterValue
from the System.Runtime.InteropServices
namespace. These approaches, while functional, were not as straightforward or consistent with the standard way of providing default values on methods.
C# 12: Default Values for Lambda Expressions
With C# 12, Microsoft has taken a significant step to further empower lambda expressions. Now, developers can specify default values for parameters in lambda expressions using the same syntax as for default parameters in methods.
Here’s a simple illustration of how it works:
var addWithDefault = (int addTo = 2) => addTo + 1;
addWithDefault(); // 3
addWithDefault(5); // 6
The example above addTo
is a parameter of the lambda expression with a default value of 2. So, when addWithDefault()
is called without any arguments, the lambda expression uses the default value, resulting in an output of 3. If a value is provided, as in addWithDefault(5)
, then the provided value is used instead, yielding an output of 6.
Interestingly, the default value can also be accessed via reflection as the DefaultValue
of the ParameterInfo
of the lambda’s Method
property, as shown below:
var addWithDefault = (int addTo = 2) => addTo + 1;
addWithDefault.Method.GetParameters()[0].DefaultValue; // 2
The addition of default values for lambda expression parameters in C# 12 marks yet another small step in the language’s evolution, enhancing its expressiveness and consistency.