Trident D'Gao
Trident D'Gao

Reputation: 19762

Why isn't a generic attribute allowed in C#?

HЕY! This topic is a duplicate of: Why does C# forbid generic attribute types?

I am looking closely at the Roslyn compiler and noticed that a generic type can be used for an attribute. Hence my question: Is there a good example of a generic attribute in C#?

EDIT:

It turned out they actually are not allowed per:

error CS0698: A generic type cannot derive from 'Attribute' because it is an attribute class

So my actual question would be: why is this this way?

Upvotes: 4

Views: 469

Answers (1)

Sam Harwell
Sam Harwell

Reputation: 100009

The metadata representation for attributes defined in ECMA-335 (CustomAttribute, §II.22.10) does not allow the constructor for an attribute to reference a MethodSpec signature, which means you could never actually use a generic attribute even if you could declare one.

The C# language was written with this restriction in mind. The specific restriction is included in §10.1.4.1 Base classes (and not repeated anywhere in §17 Attributes).

Upvotes: 5

Related Questions