Search code examples
.netgetcustomattributes

VB.net Values of Custom Attributes


I'm new to custom attributes, so I'm wondering if it is possible to get the values of the attributes. An example of the properties in my class which I use the custom attributes is:

Private mFiller As String
<Position(378), Length(34), DataType("A"), ParticipantDependant("P/D"), RequiredProperty("Required"), Format("Blank")> _
Public Property Filler() As String
   Get
      Return mFiller
   End Get
   Set(ByVal value As String)
      mFiller = value
   End Set
End Property

I'm trying to get the values of those attributes (ie. Get the Position = 378, Length = 34, etc.). The loop I was beginning with looks like this:

Dim gwlImport As New ClientGWLImport
Dim properties() As PropertyInfo = gwlImport.GetType.GetProperties
Dim tmpInfo As PropertyInfo
For Each tmpInfo In properties
   Debug.Print("Attributes for : " & tmpInfo.Name)
   For Each tmpAttribute As Object In tmpInfo.GetCustomAttributes(True)
      Debug.Print(tmpAttribute.ToString)
   Next tmpAttribute
Next tmpInfo

This gets me the names of all the attributes, but I'm not sure how to get the values. Any ideas?

Cheers,

Ryan


Solution

  • You will need to know the type of the attribute.

    For example:

    Dim posAtt As PositionAttribute 
    posAtt = CType(tmpInfo.GetCustomAttributes(GetType(PositionAttribute), True)(0), PositionAttribute)
    'Use some property of posAtt
    

    By the way, you don't need to create a new ClientGWLImport to get its Type object.
    Instead, you can write

    Dim properties() As PropertyInfo = GetType(ClientGWLImport).GetProperties()