Quick sanity check: covariance, contravariance, lack of variance inC#

  • Thread starter Thread starter raylopez99
  • Start date Start date
R

raylopez99

What are these terms in my header anyway?

But more importantly for me, look at this code:

Lack of variance:
why a List<Banana> isn’t a List<Fruit>

Many people initially expect the following code to compile:

List<Banana> bananas = new List<Banana>();
List<Fruit> fruit = bananas;

//however, it fails to compile (from Jon Skeet's cheat sheet)

However, this should work, right??:

List <Fruit> mybaseFruit = new List <Fruit>();

class Banana: Fruit {}

Banana myBanana = new Banana(); //note, this is NOT a list, but an
instantiation of a derived class Banana having base class Fruit

mybaseFruit.Add(myBanana); //should work, right? Otherwise what's the
point of inheritance?

RL
 
hi Ray,
Many people initially expect the following code to compile:

List<Banana> bananas = new List<Banana>();
List<Fruit> fruit = bananas;
This should work:

List<Fruit> fruit = (Fruit)bananas;


mfG
--> stefan <--
 
This should work:

You cannot cast between the two lists (assuming you meant (List<Fruit>),
not (Fruit)).

The closest you can get is a generic method:

static void AddFruit<T>(IList<T> list, T item) where T : Fruit
{
list.Add(item);
}

(Add isn't a good choice because the caller could do that moer
conveniently directly, but searching etc would work in the above, using
properties from the base Fruit class)

Marc
 
hi Marc,

Marc said:
You cannot cast between the two lists (assuming you meant (List<Fruit>),
not (Fruit)).
Indeed I meant (Fruit), I have not read carefully enough.
The closest you can get is a generic method:

static void AddFruit<T>(IList<T> list, T item) where T : Fruit
{
list.Add(item);
}
Maybe an Adapter is a solution, like ArrayList.Adapter(). Which is in
fact a kind of your supposed generic method.


mfG
--> stefan <--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top