I'm getting the following exception:
Unable to cast object of type 'MyClass`1[DerivedClass]' to type 'MyClass`1[BaseClass]'.
An implicit cast is attempted after I try to return an object of type MyClass(of DerivedClass) from a function call. Is there a way to explicitly cast this?
Public Class IClass(Of T)
GetModel() as T
End Class
Public Class MyClass(Of T)
Implements IClass (of T)
Public Function GetModel() As T Implements IClass(Of T).GetModel
Return _model
End Function
'Other methods/properties omitted for brevity
End Class
Public BaseClass
...
End Class
Public DerivedClass
Inherits BaseClass
...
End Class
In this example I am attempting to explicitly cast, in my program there is an implicit cast. However both lead to the same result of not being able to cast (though one is at run time and one will not compile)
Dim c1 As New MyClass(Of DerivedClass)
Dim c2 = TryCast(c1, MyClass(Of BaseClass))
Edit: I thought I simplified my example enough to not need to show any code but I guess not based on comments. So I added some example code.
Though I would prefer responses to be written in vb.net, C# is acceptable too (whichever you are more comfortable with).
I am only slightly familiar with the concept of generic variance (only just stumbled upon while attempting to find a solution to my current problem), so if that is the solution a detailed explanation or link would be appreciated.