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.

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

Exercises

  1. Remove AllowMultiple and read the compiler error for the second attribute.
  2. Write an attribute for a parameter and read it from the ParameterInfo of the method.
  3. Read the JsonPropertyName of every property of Tagged.
  4. 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.

  1. Which class must a custom attribute derive from?

    Answer

    Attribute

    The compiler accepts an attribute class only when it derives from System.Attribute.

  2. What does AttributeUsage set?

    Answer

    The targets the attribute may be applied to and its rules

    Targets, AllowMultiple and Inherited are the three settings.

  3. 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.

  4. What does AllowMultiple = true permit?

    Answer

    Several instances of the attribute on one target

    Without it the compiler reports CS0579 for a duplicate.

  5. 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.

  6. How are attributes read?

    Answer

    With reflection, at run time

    An attribute is metadata; a program reads it with GetCustomAttributes.

  7. 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.

  8. What does GetCustomAttribute<T>() return when the attribute is absent?

    Answer

    null

    The caller checks it or says it knows the attribute is there.

  9. 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.

  10. 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