Skip to content

Default lambda parameters C# 12.0code reduction

Allow a lambda's parameters to specify default values.

Optional arguments C# 4.0 allow parameters to a method to assume a default in the absence of an explicit passed value.

C# 12.0 extends this to lambda expressions C# 3.0.

Code ​

csharp
var increment = (int x, int y = 1) => x + y;
csharp
var increment = (int x, int y) => x + y;
var incrementBy1 = (int x) => increment(x, 1);

Notes ​

  • The default value is part of the lambda's inferred delegate type, so it only applies when called through var (or a delegate type declaring the same default); assigning the lambda to Func<int, int, int> drops it and produces warning CS9099
  • C# 12 also allows params arrays on lambda parameters, such as (params int[] values) => values.Sum()

More information ​

Powered by Intracia