Generics and Attributes (C# Programming Guide)

Attributes can be applied to generic types in the same way as non-generic types. For more information on applying attributes, see Attributes (C# Programming Guide).

Custom attributes are only permitted to reference open generic types, which are generic types for which no type arguments are supplied, and closed constructed generic types, which supply arguments for all type parameters.

The following examples use this custom attribute:

class CustomAttribute : System.Attribute
{
    public System.Object info;
}

An attribute can reference an open generic type:

public class GenericClass1<T> { }

[CustomAttribute(info = typeof(GenericClass1<>))]
class ClassA { }

Specify multiple type parameters using the appropriate number of commas. In this example, GenericClass2 has two type parameters:

public class GenericClass2<T, U> { }

[CustomAttribute(info = typeof(GenericClass2<,>))]
class ClassB { }

An attribute can reference a closed constructed generic type:

public class GenericClass3<T, U, V> { }

[CustomAttribute(info = typeof(GenericClass3<int, double, string>))]
class ClassC { }

An attribute that references a generic type parameter will cause a compile-time error:

//[CustomAttribute(info = typeof(GenericClass3<int, T, string>))]  //Error 
class ClassD<T> { }

A generic type cannot inherit from Attribute:

//public class CustomAtt<T> : System.Attribute {}  //Error

To obtain information about a generic type or type parameter at run time, you can use the methods of System.Reflection. For more information, see Generics and Reflection (C# Programming Guide)

See Also

Concepts

C# Programming Guide

Attributes Overview

Reference

Generics (C# Programming Guide)