I’ve got two classes, MyClassA and MyClassB. MyClassB inherits from MyClassA. I’ve written a method with the following signature
public void DoSomething(MyGeneric<MyClassA> obj);
I’ve also got the following event handler.
public void MyEventHandler(Object source, EventArgs e)
{
//source is of type MyGeneric<MyClassB>
DoSomething((MyGeneric<MyClassA>)obj);
}
I understand that MyGeneric<MyClassA> is not of the same type MyGeneric<MyClassB> but since MyClassB is a subclass of MyClassA is there still a way to make this work?
For reference, the exact error message:
Unable to cast object of type
‘MSUA.GraphViewer.GraphControls.TreeNode1[MSUA.GraphViewer.GraphControls.MaterialConfigControl]'1[MSUA.GraphViewer.PopulatableControl]’.
to type
'MSUA.GraphViewer.GraphControls.TreeNode
This is type contravariance in generics.
Even though
Bis a subtype ofA,Generic<B>is not a subtype ofGeneric<A>,so you can’t cast
Generic<B>toGeneric<A>.Check: http://msdn.microsoft.com/en-us/library/dd799517.aspx for more details.
You can overload
DoSomething()toDoSomething(Generic<B>), this method can then convertGeneric<B>toGeneric<A>and callDoSomething(Generic<A>).