Generics type parameter attributes

Hello,

I've been reading the C# 2.0 Language Specification and have come across something I don't quite understand. In the section detailing generics, the following definitions are given:

type-parameter-list:
< type-parameters >

type-parameters:
type-parameter
type-parameters, type-parameter

type-parameter:
attributes
opt identifier

The last line surprised me... I've never seen attributes used in a type parameter list. Are there any examples of such a construction being used in real-world code Am I reading this incorrectly or does this say that something like:

class C<T, [attr]U> {}

would be a legal construction

Go easy on me.. I new to this :)
- Justin Voshell




Answer this question

Generics type parameter attributes

  • Zingam

    yes you have read it correctly. Attributes are targetted for a metatool which can process them.

    Imagine you are building a component library which where components can be chained. Each layer implements the same interface. The components can be chained:

    interface ILayer1 {}
    interface ILayer2 {}

    class Component1L1 : ILayer1 {}
    class Component1L2<ILayer1> : ILayer2 {}
    ...

    so you can compose such components in this way

    Component1L2<Component1L1> chain;

    To validate composition rules you may write a component building tool which can also validate the chainig rules. The chaining rules will be then stored as attributes placed on the GenericParameters

    class Component2L2<[Family("Interactive")]ILayer1> : ILayer2 {}

    The component chain building tool will then follow the specified constraints.


  • Generics type parameter attributes