I played with generics and I saw some strange things. Hope you guys have an explanation! To keep things simple, I put the βproblemβ as an example:
namespace Lab { public class Animal { public Animal(string sound) { this.Sound = sound; } public string Sound { get; private set; } public void Kick() { Printer.Print(this, Sound); } } public class Dog : Animal { public Dog() : base("Bark, bark! I'll bite you!") { } } public class Printer { public static void Print<T>(T obj, string message) { System.Console.WriteLine("{0} says '{1}' \n", typeof(T).FullName.PadRight(10), message); } } public static class Program { static void Main(string[] args) { Animal bird = new Animal("Tweet!"); Dog dog = new Dog(); System.Console.WriteLine("Kick bird:"); bird.Kick(); System.Console.WriteLine("Kick dog:"); dog.Kick(); System.Console.WriteLine("Print kick dog:"); Printer.Print(dog, dog.Sound); System.Console.ReadLine(); } } }
So, I have two animals in my laboratory: a dog and a bird. When I "kick" these animals, they will make a sound. The printer will print the sound and type of animal. When I run the program, it prints:
Kill the bird: Lab.Animal says: "Tweet!"
Shock dog: Lab.Animal says: "Bark, bark! I will bite you!"
Type a pin-dog: Lab.Dog says: "Bark, bark! I'll bite you!"
Why does the dogβs first blow tell me that it is a Lab.Animal type? And ... how can I return it to Lab.Dog ?
Kees C. Bakker
source share