C# Casting Generic<B> to Generic<A> where B : A

Viewed 830

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]' to type 'MSUA.GraphViewer.GraphControls.TreeNode1[MSUA.GraphViewer.PopulatableControl]'.

3 Answers
Related