Roman Starkov
Roman Starkov

Reputation: 61512

How to specify a custom attribute on a generic parameter in VB.NET?

Textbook question, but I've done my googling, and I couldn't find anything.

Given a custom attribute named SomeAttribute, how do you do the following, in VB.NET?

void SomeMethod<[Some] T>()
{
}

I tried this:

Sub SomeMethod(<Some> Of T)()
End Sub

and

Sub SomeMethod(Of <Some> T)()
End Sub

But both fail to compile, with the error pointing at <Some>.

Upvotes: 2

Views: 629

Answers (1)

Roman Starkov
Roman Starkov

Reputation: 61512

Given the silence here, and because I really needed an answer, I dug into the VB.NET Language Specification.

It never says explicitly whether this is supported or not, but it does have some formal grammar definitions which suggest that this isn't supported by VB.NET.

Specifically, section 9.2.1 defines the following productions for method declaration:

SubSignature  ::=  Sub  Identifier  [  TypeParameterList  ]
    [  OpenParenthesis  [  ParameterList  ]  CloseParenthesis  ]

In 9.2.5, parameters are defined as follows:

ParameterList  ::=
    Parameter  |
    ParameterList  Comma  Parameter

Parameter  ::=
    [  Attributes  ]  [  ParameterModifier+  ]  ParameterIdentifier  [  As  TypeName  ]
            [  Equals  ConstantExpression  ]

And section 13.3 defines TypeParameterList:

TypeParameterList  ::=
    OpenParenthesis  Of  TypeParameters  CloseParenthesis

TypeParameters  ::=
    TypeParameter  |
    TypeParameters  Comma  TypeParameter

TypeParameter  ::=
    [  VarianceModifier  ]  Identifier  [  TypeParameterConstraints  ]

VarianceModifier  ::=
    In  |  Out

TypeParameterConstraints  ::=
    As  Constraint  |
    As  OpenCurlyBrace  ConstraintList  CloseCurlyBrace

ConstraintList  ::=
    ConstraintList  Comma  Constraint  |
    Constraint

Constraint  ::=  TypeName  |  New  |  Structure  |  Class

Attributes make an appearance in the parameter list (and, for functions, in the return type), but the TypeParameterList is completely devoid of anything related to attributes.

So I'm going to go ahead and claim that VB.NET 10 (shipping with VS2012) does not support attributes on generic type parameters.

Upvotes: 4

Related Questions