C # inheritance in generic question

I have two interfaces:

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

Later, I mostly use a dictionary like this:

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

C # says that I cannot convert from right to left, even if I drop it. Is there a way to use generics in C # so that this can work? If I make them abstract classes, that will be fine, but I need these interfaces.

+6
generics inheritance c #
Nov 10 2018-10-10
source share
3 answers

The function you are looking for is called conditional variance (covariance and contravariance). There is limited support for this, starting with the .net framework 4. Here's an interesting post: How is generic covariance and contra-variance generated in C # 4.0?

And here 's the MSDN entry for covariance and contravariance in wagons .

+11
Nov 10 '10 at 16:45
source share

No, this is a covariance problem. If you could do:

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

It would be possible if the compiler error did not put an object of type A in the dict.

The problem is that the dict looks like this: Dictionary<int, A> , but actually it is a type of Dictionary<int, B>() (therefore placing an object of type A will lead to a runtime error at runtime due to invalid transfer) so you should not be allowed to even try to put an object of type A in a dict, so you cannot do:

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

This will protect you from a runtime error.
Do you want to check Eric Lippert's blog on: http://blogs.msdn.com/b/ericlippert/

This is one of his favorite topics to talk about, so it’s detailed enough.

+7
Nov 10 '10 at 16:45
source share

I do not think that you will find a way around your problem, because thinking behind it seems erroneous. To illustrate, let me create another interface:

 public interface C : A { void cMethod(); } 

Now, use your code:

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

What happens when I try to do the following?

 C c = new ClassThatImplementsC(); dict.Add(1, c); 

Take a look at the Eric Lippert Covariance and Contravarience FAQ for many, many more details.

0
Nov 10 '10 at
source share



All Articles