Why doesn't C# allow generic types to be used as attributes inside the generic class?

Viewed 183

This isn't a very important question, I'm only curious why it's not allowed. The error message is not helpful in explaining, because obviously 'Att' does inherit from Attribute.

public class Generic<Att> where Att : System.Attribute
{
    [Att] //Error: 'Att' is not an attribute class
    public float number;
}
1 Answers

Attribute must be defined at compile time only because it's stored in dll or exe. And can contain only compile time created informaion. So, it can not be generic by this reason.

Compiler often uses attribute type or it's value, so you can't define it later.

In you example you want to mark field with generic parameter:

public class Generic<Att> where Att : System.Attribute
{
    [Att] //Error: 'Att' is not an attribute class
    public float number;
}

But it's equal to:

public class Generic<Att> where Att : System.Attribute
{
    [Attribute]
    public float number;
}

Because Att can not be replaced in future. So, no reason to use generics for attributes.

Related