Search code examples
vb.netinheritanceattributescustom-attributes

Should this really return an empty String()?


I have an attribute class:

<AttributeUsage(AttributeTargets.Property)> _
Public Class DirectoryAttribute
    Inherits Attribute

    Private _attribute As String

    Public Sub New(ByVal attribute As String)
        _attribute = attribute
    End Sub

    Public ReadOnly Property Attribute As String
        Get
            Return _attribute
        End Get
    End Property
End Class

And interfaces and classes:

Public Interface IDirentoryEntity
    <DirectoryAttribute("Name")> _
    Property Name As String
End Interface

Public Interface IOrganizationalUnit
    Inherits IDirectoryEntity
End Interface

Public Class OrganizationalUnit
    Implements IOrganizationalUnit

    ' Implementing IOrganizationalUnit here...'
End Class

Public Interface IIdentifiableDirectoryEntity
    Inherits IDirectoryEntity

    <DirectoryAttribute("sAMAccountName")> _
    Property Login As String
End Interface

Public Interface IGroup
    Inherits IIdentifiableDirectoryEntity
End Interface

Public Class Group
    Implements IGroup

    Private _attributes() As String

    ' Implementing IGroup here...'

    Private ReadOnly Property Attributes() As String()
        Get
            If (_attributes Is Nothing) Then
                Dim attr() As DirectoryAttribute = _
                    CType(GetType(Group).GetCustomAttributes(GetType(DirectoryAttribute), True), DirectoryAttribute())

                If (attr Is Nothing OrElse attr.Length = 0 OrElse attr(0) Is Nothing) Then _
                    Return New String(0) { }

                _attributes = New String(attr.Length) { }

                For index As Integer = 0 To attr.Length - 1 Or _attributes.Length - 1 Step 1
                    _attributes(index) = attr(index).Attribute
                Next
            End If

           Return _attributes
        End Get
    End Property
End Class

With that said, shall the Private Property Attributes() As String() not return the values of DirectoryAttribute placed over the interfaces properties as well, since I specify True in the inheritance parameter of the Type.GetCustomAttributes method?


Solution

  • I think there are two main points of confusion:

    1. Your code is looking up attributes on a type, and the attributes are applied to properties. If you want to retrieve the attribute, you'll need to look them up on a property like Login or Name.
    2. Regardless, there's a difference between inheritance and implementation. The class Group implements the interface IGroup, so you won't see any attributes defined on IGroup show up when you ask for inherited attributes on Group. If you want attributes on an interface that a type implements, you'll need to ask about the interface directly, you can't go through the type.