Skip to main content

How to Use a Constant as an Attribute Argument in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

An attribute's arguments are fixed when your code is built, so they must be constants. That's why [Description(Hours)] builds when Hours is a const and fails when it's static readonly.

Microsoft's guide to the compiler errors: Arguments to attribute constructors must be compile-time constants. The guide to applying attributes lists what an argument can be, starting with Constant expressions (literals, const/Const values, and enum values). The reason: The attribute is emitted into metadata when you compile your code. A const field qualifies, so one constant can feed both an attribute and your code.

Syntax​

Syntax
public const <type> <Name> = <value>;

[<Attribute>(<Name>)]
<declaration>
PartWhat it is
const <type> <Name>A constant, such as public const string Hours. Its value is fixed when the code is built
<value>A constant expression: a literal, or other constants combined
[<Attribute>(<Name>)]The attribute, with the constant as its argument
<declaration>What the attribute is on, such as a method

The const reference on <value>: A constant expression is an expression that the compiler can fully evaluate at compile time.

The Example​

A console app called ConstAttributeArgument has a Shop class with a constant for its opening hours. The constant is the argument of a Description attribute on the OpeningHours method, and also the text that method returns. The program prints both.

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 ConstAttributeArgument
cd ConstAttributeArgument
Output
The template "Console App" was created successfully.

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

dotnet new console -n ConstAttributeArgument creates a folder named ConstAttributeArgument 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 ConstAttributeArgument.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the code that reads the attribute:

Program.cs (reading the attribute)
using System.ComponentModel;
using System.Reflection;

// Read the Description attribute of OpeningHours and print it next to the method's result.
MethodInfo method = typeof(Shop).GetMethod(nameof(Shop.OpeningHours))!;
DescriptionAttribute description = method.GetCustomAttribute<DescriptionAttribute>()!;

Console.WriteLine($"Attribute: {description.Description}");
Console.WriteLine($"Method: {Shop.OpeningHours()}");
  • typeof(Shop).GetMethod(nameof(Shop.OpeningHours)) finds the OpeningHours method by its name. The ! tells the compiler it's there.
  • GetCustomAttribute<DescriptionAttribute>() reads the method's Description attribute. The .NET reference: Retrieves a custom attribute of a specified type that is applied to a specified member.
  • The two Console.WriteLine lines print the attribute's text, then what the method returns.

Then the class:

Program.cs (the class)
static class Shop
{
// A const is fixed when the code is built, so an attribute can use it.
public const string Hours = "Open 9:00 to 17:00, Monday to Saturday";

// The same constant as the attribute's argument and as the method's result.
[Description(Hours)]
public static string OpeningHours() => Hours;
}
  • public const string Hours is the constant. Its value is fixed when the code is built.
  • [Description(Hours)] passes the constant to the attribute. Inside Shop, the short name Hours is enough.
  • OpeningHours() returns the same constant, so the attribute and the method can't drift apart.

Step 3: Run It​

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

Terminal
dotnet run
Output
Attribute: Open 9:00 to 17:00, Monday to Saturday
Method: Open 9:00 to 17:00, Monday to Saturday

macOS-style terminal window titled Terminal — ConstAttributeArgument showing dotnet run printing Attribute: Open 9:00 to 17:00, Monday to Saturday and Method: Open 9:00 to 17:00, Monday to Saturday

Both lines show Open 9:00 to 17:00, Monday to Saturday: once read from the attribute with reflection, once returned by the method. The text is written once, in Hours, so a change there reaches the attribute and the method alike.

The Complete File​

macOS-style code window titled Program.cs — ConstAttributeArgument showing reflection code that reads the Description attribute of Shop.OpeningHours and prints it next to the method's result, and a static class Shop with a public const string Hours used as the Description attribute's argument and as the method's return value

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

// Read the Description attribute of OpeningHours and print it next to the method's result.
MethodInfo method = typeof(Shop).GetMethod(nameof(Shop.OpeningHours))!;
DescriptionAttribute description = method.GetCustomAttribute<DescriptionAttribute>()!;

Console.WriteLine($"Attribute: {description.Description}");
Console.WriteLine($"Method: {Shop.OpeningHours()}");

static class Shop
{
// A const is fixed when the code is built, so an attribute can use it.
public const string Hours = "Open 9:00 to 17:00, Monday to Saturday";

// The same constant as the attribute's argument and as the method's result.
[Description(Hours)]
public static string OpeningHours() => Hours;
}

Common Mistakes​

MistakeWhat happensDo this instead
A static readonly field as the argument[Description(Hours)] with public static readonly string Hours didn't build: error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter typeMake it a const. The const reference: although a const field is a compile-time constant, the readonly field can be used for run-time constants
A property as the argumentpublic static string Hours => "..." as the argument failed the same way, with error CS0182Use a const field
A value worked out while the program runs[Description($"Checked in {DateTime.Now.Year}")] failed with error CS0182 tooKeep run-time values out of attributes: an attribute's arguments are fixed when the code is built

FAQ​

Can the constant be built from other constants?​

Yes. With const string Days = "Monday to Saturday"; and public const string Hours = $"Open 9:00 to 17:00, {Days}";, the attribute [Description(Hours)] built, and reflection printed Open 9:00 to 17:00, Monday to Saturday. The const reference: Interpolated strings can be constants if all expressions used are also constant strings.

Can every constant be an attribute argument?​

No, its type matters too. An attribute whose constructor takes a decimal, given public const decimal CoffeePrice = 2.50m;, didn't build: error CS0181: Attribute constructor parameter 'amount' has type 'decimal', which is not a valid attribute parameter type. The guide to applying attributes: The types sbyte, ushort, uint, ulong, decimal, nint, and nuint aren't valid attribute parameter types, even though they support literal constants.

Conclusion​

An attribute argument has to be a constant, so keep a value that an attribute shares with your code in a const field. A static readonly field, a property or a value worked out at run time fails with CS0182.

Additional Resources​