Skip to content

Simple lambda parameters with modifiers C# 14.0code reduction

Use parameter modifiers without specifying types in simple lambda syntax.

Lambda expressions with parameter modifiers (ref, out, in, params) required explicit type declarations, even when the type could be inferred from context. This made lambdas with modifiers more verbose than necessary.

C# 14.0 allows parameter modifiers to be used without explicit types when the type can be inferred, making modifier-based lambdas as concise as regular lambdas.

Code

C#
// Type inferred with ref modifier
Func<int, int> increment = ref x => ref x;

// Type inferred with in modifier
Action<int> display = in x => Console.WriteLine(x);

// Type inferred with out modifier
TryParse tryParse = (string s, out value) => int.TryParse(s, out value);

// Type inferred with params
Func<int[], int> sum = params numbers => numbers.Sum();
C#
// Required explicit type with modifier
Func<int, int> increment = (ref int x) => ref x;

// Required explicit type
Action<int> display = (in int x) => Console.WriteLine(x);

// Required explicit type
TryParse tryParse = (string s, out int value) => int.TryParse(s, out value);

// Required explicit type
Func<int[], int> sum = (params int[] numbers) => numbers.Sum();

Notes

  • The compiler infers parameter types from the delegate type, just like regular lambdas
  • Works with ref, out, in, and params modifiers
  • Single-parameter lambdas with modifiers can omit parentheses: ref x => ...
  • Multi-parameter lambdas still require parentheses: (ref x, in y) => ...
  • Reduces verbosity when the type is obvious from context
  • Type inference follows the same rules as lambdas without modifiers

More information