Export (0) Print
Expand All

5.2.2 Attribute Arguments

Visual Studio .NET 2003

Arguments to an attribute may take two forms: positional arguments and instance variable/property initializers. Any positional arguments to the attribute must precede the instance variable/property initializers. A positional argument consists of a constant expression or a GetType expression. An instance variable/property initializer consists of an identifier, which can match keywords, followed by a colon and equal sign, and terminated by a constant expression or a GetType expression.

Given an attribute with attribute class T, positional argument list P, and instance variable/property initializer list N, these steps determine whether the arguments are valid:

  1. Follow the compile-time processing steps for compiling an expression of the form New T(P). This either results in a compile-time error or determines a constructor on T that is most applicable to the argument list.
  2. If the constructor determined in step 1 has parameters that are not attribute types or is inaccessible at the declaration site, a compile-time error occurs.
  3. For each instance variable/property initializer Arg in N:
    1. Let Name be the identifier of the instance variable/property initializer Arg.
    2. Name must identify a non-Shared, writeable, Public instance variable or parameterless property on T whose type is an attribute type. If T has no such instance variable or property, a compile-time error occurs.

For example:

Imports System

<AttributeUsage(AttributeTargets.All)> _
Public Class GeneralAttribute
    Inherits Attribute

    Public Sub New(ByVal x As Integer)
    End Sub

    Public Sub New(Byval x As Double)
    End Sub

    Public y As Type

    Public Property z As Integer
        End Get

        End Set
    End Property
End Class

' Calls the first constructor.
<General(10, z := 30, y := GetType(Integer))> _
Class Foo
End Class

' Calls the second constructor.
<General(10.5, z := 10)> _
Class Bar
End Class
AttributeArguments ::=
   AttributePositionalArgumentList |
   AttributePositionalArgumentList , VariablePropertyInitializerList |
AttributePositionalArgumentList ::=
   ConstantExpression |
   AttributePositionalArgumentList , ConstantExpression
VariablePropertyInitializerList ::=
   VariablePropertyInitializer |
   VariablePropertyInitializerList , VariablePropertyInitializer
VariablePropertyInitializer ::=
   IdentifierOrKeyword : = ConstantExpression

See Also

5.1 Attribute Classes | 5.2 Attribute Blocks | 5.2.1 Attribute Names | 5. Attributes | Attributes (Visual Basic Language Concepts)

© 2014 Microsoft