.NET 8 and C# 12 — Default Lambda Parameters
Default Lambda Parameters it’s a new C# 12 feature which allows you to define a default value for a parameter in lambda expressions. In this article, I present how to use this feature.
For demonstration purposes, I created a console application with .NET 8, and I configured the LangVersion
in the .csproj file with the preview
value:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
</PropertyGroup>
</Project>
To create a default lambda parameter, the syntax and the rules are the same as adding default values for arguments to any method or local function. To create a lambda with a default parameter value, you only need to specify the value of the parameter, for example:
var lambdaDemo = (string name = "User") => Console.WriteLine($"Hello {name}");
This means that if the lambda is now called, without passing any parameter, the default value will be used:
lambdaDemo();
// Output:
Hello User
When calling the lambda informing a parameter, the default value will then not be used:
lambdaDemo("Gandalf");
// Output:
Hello Gandalf
It’s also possible to retrieve the lambda’s default parameter value. For that, you need to use the property Method
, and call the GetParemeters
informing the position of the parameter you wanna retrieve (in this example there is only one parameter, so for this reason is the position 0
):
lambdaDemo.Method.GetParameters()[0].DefaultValue}
// Output:
User
Conclusion
Default Lambda Parameters it’s a new C# 12 feature that allows you to define default values for parameters on lambda expressions, making it possible now to execute lambda expressions without needing to always inform a parameter value.
This is the link for the project in GitHub: https://github.com/henriquesd/DotNet8Examples
If you like this demo, I kindly ask you to give a ⭐️ in the repository.
Thanks for reading!