11

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;
}
user7486517
  • 191
  • 1
  • 7

1 Answers1

2

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.

Backs
  • 24,430
  • 5
  • 58
  • 85
  • 6
    But a generic type **is** a compile-time type. – MakePeaceGreatAgain Jan 09 '19 at 11:42
  • @HimBromBeere so, what will you store in binary dll? `Att` type only? You can not override it later. No reason to declare it via generic. – Backs Jan 09 '19 at 11:44
  • 2
    `[MyAttribute]` instead of `[MyAttribute(typeof(int))]` is a clear use case where this could improve (somewhat) syntax. And some sources actually listed this feature like a possibility in C# 8: [C# 8.0 - New Planned Features](https://www.dotnetcurry.com/csharp/1440/csharp-8-new-features) – InBetween Jan 09 '19 at 12:03