C# Reference ยท Reflection, Attributes and Metadata
Generic attributes in C#
Reference for generic attributes in C# 11: declare Attribute<T> classes, apply them with a type argument, read them with reflection and avoid typeof.
Since C# 11 an attribute class can be generic. Before that, an attribute that needed to carry a type had to take a Type parameter and be written with typeof(...), so the compiler could not check anything about that type. With a generic attribute the type is a real type argument: [Serializer<OrderSerializer>] instead of [Serializer(typeof(OrderSerializer))]. Constraints such as where T : IFormatter are checked at compile time.
You declare one by deriving a generic class from System.Attribute. You apply it by writing the type argument in angle brackets after the attribute name. The Attribute suffix is optional, as with any attribute.
[AttributeUsage(AttributeTargets.Class)] public sealed class HandlerAttribute<T> : Attribute where T : class { } [Handler<string>] class Demo { }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public sealed class NameAttribute<T> : Attribute where T : constraint { ... } [Name<int>] [Name<List<string>>(Prop = value)]
| Part | Description |
|---|---|
NameAttribute<T> |
A generic class deriving directly or indirectly from System.Attribute. It may have several type parameters and constraints. |
[Name<TArg>] |
Applies the attribute. The Attribute suffix may be dropped. |
| Constructor and properties | Positional and named arguments follow the normal attribute rules: constants, typeof, nameof and arrays of those. |
Errors: the type argument must be a fully constructed type. A type parameter of the enclosing generic class cannot be used (the compiler reports CS8968: "'T': an attribute type argument cannot use type parameters"). The same is true for types that contain a type parameter, such as List<T>. Annotated nullable reference types such as [Name<string?>] fail with CS8970: "Type 'string' cannot be used in this context because it cannot be represented in metadata".
Usage notes
- At the metadata level a generic attribute is just a generic type. Reflection returns the closed type (for example
ViewModelAttribute<OrderViewModel>), soattribute.GetType().GenericTypeArgumentstells you the type argument. - Searching by the open generic type does not work with
GetCustomAttribute<T>(), because you must supply a closed type. Either ask for the closed attribute you expect, or loop overGetCustomAttributesData()orGetCustomAttributes()and compareGetGenericTypeDefinition(). - A non-generic base class is a common helper: derive
ViewModelAttribute<T>from a plainViewModelAttributethat exposes aType ModelTypeproperty. Code that only needs to find "any view-model attribute" can then use the base type. AttributeUsageworks as usual, andAllowMultiple = truelets you apply the same attribute with different type arguments.- Compile-time checks are the main benefit. A constraint rejects wrong arguments, and renaming the type with a refactoring tool updates the attribute. Strings and
typeofcannot give you that. - Not for generic arguments from the context: an attribute inside
class Box<T>cannot say[Item<T>]. If you need that, store aTypein a regular attribute or use a generic method instead. - Cost: attributes are created only when something asks for them through reflection, so using generic ones adds no work at runtime until then.