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.TreeNode
1[MSUA.GraphViewer.GraphControls.MaterialConfigControl]' to type 'MSUA.GraphViewer.GraphControls.TreeNode1[MSUA.GraphViewer.PopulatableControl]'.
This is type contravariance in generics.
Even though B is a subtype of A,Generic<B> is not a subtype of Generic<A>,
so you can't cast Generic<B> to Generic<A>.
Check: http://msdn.microsoft.com/en-us/library/dd799517.aspx for more details.
You can overload DoSomething() to DoSomething(Generic<B>), this method can then convert Generic<B> to Generic<A> and call DoSomething(Generic<A>).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With