4

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?

Community
  • 1
  • 1
Trident D'Gao
  • 18,973
  • 19
  • 95
  • 159
  • 1
    What do you need an example for? What do you consider a good example? – Chris Feb 16 '14 at 22:30
  • On the contrary, it is an error to define a generic type deriving from `Attribute`: "A generic type cannot derive from 'Attribute' because it is an attribute class." – Mike Zboray Feb 16 '14 at 22:31
  • Just pure curiosity, I cannot think of a situation where I would need an attribute to be generic, but it seems to be possible – Trident D'Gao Feb 16 '14 at 22:31
  • @mikez well that's a good news, it means I can ignore this case – Trident D'Gao Feb 16 '14 at 22:33
  • 2
    The property and constructor argument values are stored in the assembly metadata. Those values can of course never be generic. Which leaves very little use for an attribute still being generic, none that I can think of. – Hans Passant Feb 16 '14 at 22:48
  • @Chris and others who cannot see a use: For example instead of the clumsy `[Somthing(typeof(TheClass), "My text")]` it could be cool to use `[Somthing("My text")]`. One could also search for instances of the closed/constructed type `SomethingAttribute` in that case. Of course we can live without that, but it would not be completely useless. – Jeppe Stig Nielsen Feb 16 '14 at 23:17

1 Answers1

5

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).

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
  • But why can you do that in LinqPad (Version 6) with latest Roslyn code enabled? There it is working but in .NET Fiddle it is not ... – Matt Oct 08 '21 at 14:02