[quoted text, click to view] Tony Johansson wrote:
> Hello!
>
> Assume you have this generic Dictionary class with key, value pair the first
> part is the key and the second part is the value part.
> The key value is a string and the value part is the Car.
> Dictionary<string, Car> directory = new Dictionary<string, Car>();
> Now to my question assume that you have a derived class called BMW below the
> base class Car.
>
> Is it then legal to use BMW instead of Car because BMW is a Car or are you
> obliged to use exactly
> the same type (here Car) as the one you used when you instansiated the
> object directory of type Dictionary.
>
> I assume that this is the main point of using generics to use exactly the
> same type because if this was not the case you could all the same use the
> general class.
This is actually a question about polymorphism and inheritance, rather
than a question about generics.
A class (BMW) that inherits from another class (Car), is, if you think
of the classes as categories, of that base category.
A BMW is a Car.
Which leads to: Anywhere you can talk about a Car, you can use a BMW.
This also holds true for generics. The only difference is when you get
to covariance. In other words, while you can do this:
Car c = new BMW();
or this:
BMW b = new BMW();
MethodThatTakesCarParameter(b);
you can not do this:
List<Car> c = new List<BMW>();
or this:
List<BMW> b = new List<BMW>();
MethodThatTakesAListOfCars(b);
This is (apparently) supported by the runtime, but not by the C#
programming language.
The main reason is that if the above was legal, you could do this:
List<Car> c = new List<BMW>();
c.Add(new Car()); // list is only supposed to store BMW's
--
Lasse Vågsæther Karlsen
mailto:lasse@vkarlsen.no
http://presentationmode.blogspot.com/