views:

137

answers:

2

Hey,

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

+1  A: 

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()
SLaks
posAtt = tmpInfo.GetCustomAttributes(GetType(PositionAttribute), True)(0) As PositionAttribute ???? New syntax?
Codezy
Other than the syntax error, it's exactly what I'm looking for. It should read: posAtt = CType(tmpInfo.GetCustomAttributes(GetType(PositionAttribute), True)(0), PositionAttribute)
bornbnid
Sorry for the syntax error; I'm too used to C#.
SLaks
+1... I wonder why this got downvoted for a minor syntax error.
Daniel Vassallo
A: 

The System.Reflection.CustomAttributeData class exposes functionality for retrieving the complete definition of custom attributes decorating a type or member.

Nicole Calinoiu
This should only be used on code that was loaded in a reflection-only context. For normal code, you should use `GetCustomAttributes`, which will probably be faster and certainly be simpler. See my answer.
SLaks
@SLaks: Despite the fact that the CustomAttributeData class may have been originally designed to support something that would not otherwise have worked in a reflection-only context, it works just fine for a normally loaded assembly. This is explicitly stated in the documentation: "CustomAttributeData can be used in the execution context as well as in the reflection-only context."If the type of attribute is well-known, your approach would obviously be preferable. However, I read the original posting as requesting a general-purpose approach to reading full attribute data.
Nicole Calinoiu