Daniel
Daniel

Reputation: 121

.NET Inheritance/Interfaces

How to access inherited property in Generic Method?

Public Sub DoSomething(Of BusObjectType)(MyBusObject As BusObjectType)

    MyBusObject.Property1 = "Something"

End Sub

Property1 is inherited from a base class. I don't have an interface, just a base class for all my business objects.

Upvotes: 0

Views: 58

Answers (2)

D Stanley
D Stanley

Reputation: 152556

If this is all you are doing, then the method doesn't need to be generic:

Public Sub DoSomething(MyBusObject As {base class})

    MyBusObject.Property1 = "Something"

End Sub

You only need to make it generic if you are returning the value and want it to be typed properly, or calling another generic method that requires the specific type. You can pass a derived class as a parameter that is typed as the base class.

For example:

Public Sub Feed(pet As Animal)

    // feed the pet

End Sub

You can pass in a Dog, a Cat, or a Ferret (if that's your sort of thing). You don't need to have different methods for each pet type or make the method generic.

Upvotes: 1

Colin Mackay
Colin Mackay

Reputation: 19175

You can add an As BaseClassName to the generic definition to ensure that what ever it is will be of that base type.

For example:

Public Sub DoSomething(Of BusObjectType As BaseClassName)(MyBusObject As BusObjectType)

    MyBusObject.Property1 = "Something"

End Sub

See here ("Constraints" section) for more information: https://msdn.microsoft.com/en-us/library/w256ka79.aspx

Upvotes: 2

Related Questions