Question Property Attribute Retrieval

joeyt

New member
Joined
Dec 20, 2010
Messages
2
Programming Experience
1-3
I've looked around for discussion on this topic, but wasn't able to find it.

I am trying to retrieve the Attributes of a class's property specifically.

So for example. Let's say I have a class called "Employee", and a custom attribute called CustomLabelAttribute with a string value. What would I need to do to retrieve the value of CustomLabelAttribute for Employee.FirstName specifically? I assume I will need to use reflection, but it's kind of new to me, and I've just recently started using it on any level.

Thanks for your help!

VB.NET:
Public Class Employee

        Private m_FirstName As String
        <CustomLabel(value:="Employee's First Name")> _
        Public Property FirstName() As String
            Get
                Return m_FirstName
            End Get
            Set(ByVal value As String)
                m_FirstName = value
            End Set
        End Property

        Private m_MiddleName As String
        Public Property MiddleName() As String
            Get
                Return m_MiddleName
            End Get
            Set(ByVal value As String)
                m_MiddleName = value
            End Set
        End Property

        Private m_LastName As String
        Public Property LastName() As String
            Get
                Return m_LastName
            End Get
            Set(ByVal value As String)
                m_LastName = value
            End Set
        End Property

VB.NET:
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True, Inherited:=True)> _
    Public Class CustomLabelAttribute
        Inherits Attribute

        Public Sub New()
        End Sub

        Private m_Value As String
        Public Property Value() As String
            Get
                Return m_Value
            End Get
            Set(ByVal value As String)
                m_Value = value
            End Set
        End Property

    End Class
 
VB.NET:
Dim attribs() As Object = GetType(Employee).GetProperty("FirstName").GetCustomAttributes(GetType(CustomLabelAttribute), False)
Dim value As String = CType(attribs(0), CustomLabelAttribute).Value
or
VB.NET:
Dim attrib As Attribute = Attribute.GetCustomAttribute(GetType(Employee).GetProperty("FirstName"), GetType(CustomLabelAttribute))
value = CType(attrib, CustomLabelAttribute).Value
 
Great! Thanks. Would there be a way to retrieve a property's attribute dynamically? Meaning, could I create a function that would return the CustomLabelAttribute for any property I pass to it?

Thanks!
 
If you can Get a Property you can Get a Custom Attribute. GetProperty/GetProperties returns PropertyInfo objects for any type.
 

Latest posts

Back
Top