Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]'.

like image 485
Roy T. Avatar asked Jul 15 '11 12:07

Roy T.


1 Answers

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>).

like image 138
StuperUser Avatar answered Sep 30 '22 03:09

StuperUser