Skip to main content

How to Put an Attribute on a Lambda Parameter in C#

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

A lambda's parameter can carry an attribute, just like a method's parameter. Write it inside the lambda's parentheses, right in front of the parameter: ([Description(...)] double celsius) => ....

Microsoft's reference on lambda expressions: You can add attributes to a lambda expression and its parameters. What they do, and don't do: Attributes don't have any effect when the lambda expression is invoked. Attributes on lambda expressions are useful for code analysis, and can be discovered via reflection. That's why the example reads its attribute back with reflection.

Syntax​

Syntax
<DelegateType> <name> = ([<Attribute>(<arguments>)] <ParameterType> <parameter>) => <expression>;
PartWhat it is
<DelegateType>The type of the variable that holds the lambda, such as Func<double, double>
[<Attribute>(<arguments>)]The attribute, in square brackets, in front of the parameter it belongs to
<ParameterType> <parameter>The parameter. Its type can be left out when <DelegateType> already gives it
( )The parentheses around the parameters. With an attribute, they're required
<expression>What the lambda works out and returns

The reference on the parentheses: you must parenthesize the input parameters when you add attributes to a lambda expression or its parameters.

The Example​

A console app called LambdaAttribute has a lambda that turns degrees Celsius into degrees Fahrenheit. Its parameter carries a Description attribute that says what the number means, and the program reads that description back.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n LambdaAttribute
cd LambdaAttribute
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/LambdaAttribute/LambdaAttribute.csproj:
Determining projects to restore...
Restored /Users/you/source/LambdaAttribute/LambdaAttribute.csproj (in 39 ms).
Restore succeeded.

dotnet new console -n LambdaAttribute creates a folder named LambdaAttribute with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or LambdaAttribute.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the lambda, with the attribute on its parameter:

Program.cs (the lambda)
using System.ComponentModel;
using System.Reflection;

// The attribute goes in front of the parameter, inside the parentheses.
Func<double, double> toFahrenheit =
([Description("A temperature in degrees Celsius")] double celsius) => celsius * 9 / 5 + 32;
  • using System.ComponentModel; brings in DescriptionAttribute, an attribute that holds a text, and using System.Reflection; the types that read attributes.
  • [Description("A temperature in degrees Celsius")] sits inside the lambda's parentheses, in front of double celsius, so it belongs to that parameter.
  • celsius * 9 / 5 + 32 is the conversion itself.

Then call the lambda:

Program.cs (the call)
Console.WriteLine($"100 C is {toFahrenheit(100)} F");

toFahrenheit(100) runs the lambda like a method, with 100 as celsius.

Last, read the attribute back:

Program.cs (reading the attribute)
// The attribute is stored with the lambda's parameter, and reflection can read it.
ParameterInfo parameter = toFahrenheit.Method.GetParameters()[0];
DescriptionAttribute? description = parameter.GetCustomAttribute<DescriptionAttribute>();
Console.WriteLine($"Parameter {parameter.Name}: {description?.Description}");
  • toFahrenheit.Method is the method the compiler made from the lambda. The .NET reference: Gets the method represented by the delegate. GetParameters() returns its parameters, and [0] is the first one, celsius.
  • GetCustomAttribute<DescriptionAttribute>() Retrieves a custom attribute of a specified type that is applied to a specified parameter. It returns null when there's none, so the variable is a DescriptionAttribute? and the print uses description?.Description.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
100 C is 212 F
Parameter celsius: A temperature in degrees Celsius

macOS-style terminal window titled Terminal — LambdaAttribute showing dotnet run printing 100 C is 212 F and Parameter celsius: A temperature in degrees Celsius

The lambda turned 100 into 212, and reflection found the attribute on the parameter named celsius, with its text, A temperature in degrees Celsius. The attribute played no part in the calculation: it's information stored with the parameter, for code that looks for it.

The Complete File​

macOS-style code window titled Program.cs — LambdaAttribute showing a Func of double and double that converts Celsius to Fahrenheit with a Description attribute on its celsius parameter, a call with 100, and reflection code that reads the parameter's description with Method.GetParameters and GetCustomAttribute

Program.cs
using System.ComponentModel;
using System.Reflection;

// The attribute goes in front of the parameter, inside the parentheses.
Func<double, double> toFahrenheit =
([Description("A temperature in degrees Celsius")] double celsius) => celsius * 9 / 5 + 32;

Console.WriteLine($"100 C is {toFahrenheit(100)} F");

// The attribute is stored with the lambda's parameter, and reflection can read it.
ParameterInfo parameter = toFahrenheit.Method.GetParameters()[0];
DescriptionAttribute? description = parameter.GetCustomAttribute<DescriptionAttribute>();
Console.WriteLine($"Parameter {parameter.Name}: {description?.Description}");

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out the parentheses[Description("A temperature in degrees Celsius")] celsius => celsius * 9 / 5 + 32 didn't build: error CS8916: Attributes on lambda expressions require a parenthesized parameter list.Put the parameter in parentheses, even when it's the only one
Expecting the attribute to check the argumentWith ([Range(1, 5)] int count) => new string('*', count), a call with 8 printed eight stars: nothing checked the rangeCheck the value in the lambda's body. The reference: Attributes don't have any effect when the lambda expression is invoked.
An attribute that isn't allowed on parameters([Obsolete] double celsius) => ... didn't build: error CS0592: Attribute 'Obsolete' is not valid on this declaration type. It is only valid on 'class, struct, enum, constructor, method, property, indexer, field, event, interface, delegate' declarations.Use an attribute that's allowed on parameters. The compiler errors guide: Each attribute's AttributeUsageAttribute specifies which declaration types it targets.

FAQ​

Do I have to write the parameter's type?​

No. With the type left out, ([Description("A temperature in degrees Celsius")] celsius) => celsius * 9 / 5 + 32 built, printed 212, and reflection read the same description: Func<double, double> already says that celsius is a double. Only the parentheses are required.

Conclusion​

To put an attribute on a lambda's parameter, write it in front of the parameter, inside the parentheses. It changes nothing when the lambda runs: it's there for the code that reads it, through reflection or code analysis.

Additional Resources​