Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# inheritance in generics question

I have two interfaces:

public interface A { 
 void aMethod(); 
}


public interface B : A {
 void bMethod();
} 

Later I'm basically using a dictionary like this:

Dictionary<int, A> dict = new Dictionary<int, B>();

C# is saying I can't convert from the right to the left, even if I cast it. Is there a way to use generics in C# so that this can work? If I make them abstract classes it seems to be ok but I need these as interfaces.

like image 212
Daniel Murphy Avatar asked Nov 10 '10 16:11

Daniel Murphy


2 Answers

The feature you are looking for is what's referred to as generics variance (covariance and contravariance). There is limited support for this starting in .net framework 4. Here's an interesting post: How is Generic Covariance & Contra-variance Implemented in C# 4.0?

And here's the MSDN entry on Covariance and Contravariance in Generics.

like image 118
Mike Dinescu Avatar answered Oct 11 '22 12:10

Mike Dinescu


Nope it's a covariance issue. If you could do:

Dictionary<int, A> dict = new Dictionary<int, B>();

It would be possible without a compiler error to put an object of Type A in dict.

The problem is that dict looks like: Dictionary<int, A> but it is really type Dictionary<int, B>() (so placing an object of Type A would throw a runtime error because of an invalid cast), so you shouldn't be allowed to even try to place an object of Type A in dict, which is why you can't do :

Dictionary<int, A> dict = new Dictionary<int, B>();

It's protecting you from making a runtime mistake.
You want to check out Eric Lippert's blog on the subject: Link

It's one of his favorite topics to talk about, so it's quite thorough.

like image 22
kemiller2002 Avatar answered Oct 11 '22 12:10

kemiller2002