Attributes
An attribute is metadata attached to a type, a member, a parameter or an assembly. The compiler writes it into the assembly and nothing runs it; a program that cares reads it back with reflection. The framework itself is built on them: a property is serialized because an attribute said so, and a type is not used because an attribute marked it obsolete.
A custom attribute
An attribute is a class derived from Attribute. Its constructor arguments are the positional ones, and its settable properties are the named ones written in the brackets:
using System.Reflection;
var tags = typeof(Report).GetCustomAttributes<TagAttribute>();
Console.WriteLine($"count {tags.Count()}");
foreach (var tag in tags.OrderBy(t => t.Name))
{
Console.WriteLine($"tag {tag.Name} {tag.Order}");
}
var method = typeof(Report).GetMethod("Run")!;
Console.WriteLine($"method tags {method.GetCustomAttributes<TagAttribute>().Count()}");
Console.WriteLine($"usage {typeof(TagAttribute).GetCustomAttribute<AttributeUsageAttribute>()!.AllowMultiple}");
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
sealed class TagAttribute : Attribute
{
public TagAttribute(string name) => Name = name;
public string Name { get; }
public int Order { get; set; }
}
[Tag("report", Order = 2)]
[Tag("demo")]
sealed class Report
{
[Tag("entry")]
public void Run()
{
}
}
dotnet run
count 2
tag demo 0
tag report 2
method tags 1
usage True
The class carries two instances of the attribute, one with the named argument Order = 2, and the method carries one. The order of GetCustomAttributes is not promised, so the program sorts by name before it prints. AllowMultiple is what made two instances legal; without it the compiler rejects the second with error CS0579.
Where it may be applied
AttributeUsage sets the targets and the rules of an attribute, and the compiler enforces them: an attribute of a class on a method is a compile error, not a run-time surprise.
- AttributeTargets is a flags enum: Class, Method, Property, Field, Parameter, ReturnValue, Assembly, and the rest.
- AllowMultiple = true permits several instances on one target, which the example uses.
- Inherited = true (the default) lets a derived class see an attribute of its base; a member attribute is inherited with override, not with new.
- The attribute name may drop the Attribute suffix, which is why the class is TagAttribute and the use is [Tag].
Attributes of the BCL
The shared framework uses the same mechanism. The program reads three of its attributes back: a JSON name, the flags marker of an enum and the message of an obsolete method:
using System.Reflection;
using System.Text.Json.Serialization;
var name = typeof(Tagged).GetProperty("Name")!
.GetCustomAttribute<JsonPropertyNameAttribute>()!.Name;
Console.WriteLine($"json name {name}");
var flags = typeof(Permission).GetCustomAttribute<FlagsAttribute>() is not null;
Console.WriteLine($"flags {flags}");
var obsolete = typeof(Legacy).GetMethod("Old")!.GetCustomAttribute<ObsoleteAttribute>()!;
Console.WriteLine($"obsolete {obsolete.Message}");
Console.WriteLine($"error {obsolete.IsError}");
sealed record Tagged([property: JsonPropertyName("display")] string Name);
[Flags]
enum Permission
{
None = 0,
Read = 1,
Write = 2,
}
static class Legacy
{
[Obsolete("Use New instead")]
public static void Old()
{
}
}
dotnet run
json name display
flags True
obsolete Use New instead
error False
The JSON name is display, which the lesson on writing JSON used without reading the attribute. The enum is a flags enum, and the obsolete method carries a message and IsError false, so it warns the compiler instead of failing the build. A call to that method directly would produce warning CS0618; the program reads the attribute by name and avoids the call.
Reading them back
- GetCustomAttribute<T>() returns the first instance or null; the null-forgiving mark is a claim that it is there.
- GetCustomAttributes<T>() returns every instance, and the order is not promised.
- Reading an attribute runs its constructor, so an attribute that does work in its constructor does that work on every read.
- A parameter attribute is read from ParameterInfo, a return attribute from ReturnParameter, and an assembly attribute from Assembly.GetCustomAttributes.
Exercises
- Remove AllowMultiple and read the compiler error for the second attribute.
- Write an attribute for a parameter and read it from the ParameterInfo of the method.
- Read the JsonPropertyName of every property of Tagged.
- Put an Obsolete attribute with error: true on a method and call it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which class must a custom attribute derive from?
Answer
Attribute
The compiler accepts an attribute class only when it derives from System.Attribute.
-
What does AttributeUsage set?
Answer
The targets the attribute may be applied to and its rules
Targets, AllowMultiple and Inherited are the three settings.
-
What does this program print?
using System.Reflection; var tags = typeof(Report).GetCustomAttributes<TagAttribute>(); Console.WriteLine(tags.Count()); [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] sealed class TagAttribute : Attribute { } [Tag] [Tag] sealed class Report { }Answer
2
AllowMultiple permits the two instances, and both are returned.
-
What does AllowMultiple = true permit?
Answer
Several instances of the attribute on one target
Without it the compiler reports CS0579 for a duplicate.
-
What does this program print?
using System.Reflection; Console.WriteLine(typeof(TagAttribute).GetCustomAttribute<AttributeUsageAttribute>()!.AllowMultiple); [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] sealed class TagAttribute : Attribute { }Answer
True
The attribute declared AllowMultiple true on itself.
-
How are attributes read?
Answer
With reflection, at run time
An attribute is metadata; a program reads it with GetCustomAttributes.
-
What does this program print?
using System.Reflection; using System.Text.Json.Serialization; var name = typeof(Tagged).GetProperty("Name")! .GetCustomAttribute<JsonPropertyNameAttribute>()!.Name; Console.WriteLine(name); sealed record Tagged([property: JsonPropertyName("display")] string Name);Answer
display
The attribute carries the name that the serializer writes.
-
What does GetCustomAttribute<T>() return when the attribute is absent?
Answer
null
The caller checks it or says it knows the attribute is there.
-
What does this program print?
using System.Reflection; Console.WriteLine(typeof(Permission).GetCustomAttribute<FlagsAttribute>() is not null); [Flags] enum Permission { None = 0, Read = 1, }Answer
True
The enum carries the Flags attribute, so the lookup finds it.
-
Do attributes run by themselves?
Answer
No, they are metadata that code reads
The runtime or a library reads them; the compiler only records them.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev