Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Did you consider implementing an interface instead? I assume that you're using a base class as you want to provide some code in the base, if not then an Interface might be better depending on your other requirements:

Interface IBase
    ReadOnly Property CustomAttribute() As String   
End Interface

It's still very compact and when you type 'Implements IBase' in a new class Visual Studio will fill in the code for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top