views:

69

answers:

1

I'm trying to force an inherited class to use a custom attribute. I'm creating a class library where the user who wants to create an item will do so, but be forced to add an attribute (or visual studio will automatically add the default attribute) to their inherited class. Here is what I'm hoping to achieve:

BaseClass.vb:

<CustomAttribute(10)> _
Public Class BaseClass

End Class

MyClass.vb:

<CustomAttribute(12)> _
Public Class MyClass
    Inherits BaseClass

    Public Sub New()
         Mybase.New()
    End Sub

End Class

So the thought is that much like when you mark a function as "MustOverride" and then the inherited class must override the function, I want the attribute to be "MustOverride" causing the inherited class to specify the value.

I've tried this, and it will work, but it would be much cleaner if I could use attributes:

BaseClass.vb:

Public MustInherit Class BaseClass

   Public MustOverride ReadOnly Property CustomAttribute() As String

End Class

MyClass.vb:

Public Class MyClass
    Inherits BaseClass

    Public Sub New()
         Mybase.New()
    End Sub

    Public Overrides ReadOnly Property CustomAttribute() As String
        Get
             Return "testing"
        End Get
    End Property
End Class

Thank you for any help you can provide.

Scott

+1  A: 

There's no way in .NET to force a class to define an attribute at compile time. The best you'll be able to do is check at run-time whether the attribute was defined, and if not to throw an exception.

Joseph
Thats not the answer I wanted, but the answer I suspected. Thank you. - Scott
Scott
@Scott sorry, I wish I had the answer you wanted!
Joseph