user1072367
user1072367

Reputation: 11

VB.NET - Access shared member through Type

I'm wondering if this is possible. In my Test function below I want to

  1. Check if T is of type BaseClass; throw an error if it's not.
  2. Get the value of SomeText property of BaseClass.

    Class BaseClass
    
        Public Shared Property SomeText As String
    
    End Class
    
    Class Class1
        Inherits BaseClass
    
        Public Sub New()
            SomeText = "Class 1 here"
        End Sub
    
    End Class
    

...

    Sub Main

        Test(GetType(Class1))
        Test(GetType(Class2))

    End Sub

    Sub Test(T As Type)

        ' Task 1: Check if T is of type BaseClass

        ' Task 2: Get the value of SomeText property of BaseClass

    End Sub

Upvotes: 1

Views: 736

Answers (2)

competent_tech
competent_tech

Reputation: 44921

Rewrite test as follows (updated to reflect change to question):

Sub Test(T As Type)

    ' Task 1: Check if T is of type BaseClass
    If T.IsSubclassOf(GetType(BaseClass)) Then
       ' Task 2: Get the value of SomeText property of BaseClass
        Dim sValue As String
        ' Create an unused instance of BaseClass to ensure the current value of SomeText is assigned
        Dim oClass As BaseClass = DirectCast(System.Activator.CreateInstance(T), BaseClass)

        ' Get the value from BaseClass since it is a shared instance
        sValue = BaseClass.SomeText
    Else
       Throw New ArgumentException("T did not inherit from BaseClass")
    End If


End Sub

Upvotes: 1

Jay
Jay

Reputation: 6017

You can keep your test signature and do the following:

    If T.BaseType Is GetType(BaseClass) Then
        Dim CurrentValue as String = BaseClass.SomeText
    Else
        Throw New ArgumentException("T must inherit from BaseClass")
    End If

Since this never actually creates an instance of your type, you may not get the string you are expecting. If you haven't created an instance elsewhere you will only have an empty string.

You can generate an instance of your class from the type you sent if that is your goal:

    If T.BaseType Is GetType(BaseClass) Then
        Dim currentValue As String = CType(Activator.CreateInstance(T), BaseClass).SomeText
    Else
        Throw New ArgumentException("T must inherit from BaseClass")
    End If

Edit based on Comment about further subclassing:

If you want it to include the base type or any descendants you could use this if instead:

    If T Is GetType(EventBase) OrElse T.IsSubclassOf(GetType(EventBase)) Then

    End If

Upvotes: 2

Related Questions