In the below example, I can add have a List
of type Animal
. Since Dog
and Cat
derive from animal, the List
can hold each. However, if I have a method that accepts List<Animal>
, you can not pass in a reference List<Dog>
. If Dog
is derived from animal, why is this not valid? However if i have a method that excepts a parameter of type Object
, and all objects derive from Object
, it works.
class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>();
animals.Add(new Dog() { Color = "Black" }); // allowed since Dog derives from Animal
List<Dog> dogs = new List<Dog>();
dogs.Add(new Dog() { Color = "White" });
Test(animals);
Test(dogs); // not allowed - does not compile
Test2(dogs); // valid as all objects derive from object
}
static void Test(List<Animal> animals) {
// do something
}
static void Test2(object obj) {
}
}
public class Animal {
public String Color { get; set; }
}
public class Dog : Animal { }
public class Cat : Animal { }