Euregan Euregan - 5 months ago 8
Vb.net Question

Function overloads based on interface inheritance

Say I have a base interface, and another one inheriting from it :

Public Interface Parent
{stuff}
End Interface


And

Public Interface Child
Inherits Parent
{other stuff}
End Interface


I also have a sub and its overload :

Public Sub doStuff(parameter As Parent)
{do some stuff}
End Sub


And

Public Sub doStuff(parameter As Child)
{do some other stuff}
End Sub


If I call the sub like this it calls the "child function" :

Dim myParam As Child = New SomeClassImplementingChild
doStuff(myParam)


However, is there any way to make it call the "child function" with something like this, assuming I don't know at compile time the type of the coolParameter :

Public Sub coolFunction(coolParameter As Parent)
doStuff(coolParameter)
End Sub

Dim myParam As Child = New SomeClassImplementingChild
coolFunction(myParam)

Answer

I have found a workaround which is I guess the closest I'll ever get to a solution:

doStuff(Convert.ChangeType(coolParameter, coolParameter.GetType))

That will convert to the "real" type at Runtime, effectively calling the right function. However, the functions all have to be public to be called that way