Example #1
0
        public static void Main(string[] args)
        {
            // Suppose I have a few collections of animals.
            Iguana[] igs     = new Iguana[] { new Iguana() };
            Rat[]    rats    = new Rat[] { new Rat() };
            Animal[] animals = new Animal[] { new Iguana(), new Rat() };

            // Which of these function calls is valid?

            /*
             * PrintAnimal(igs[0]);
             * PrintAnimal(animals[0]);
             * PrintIguana(animals[0]);
             * PrintRat(igs[0]);
             * PrintRat(rats[0]);
             *
             * Why??
             */

            // How about these?

            /*
             * PrintAnimals(animals);
             * PrintAnimals(igs);
             * PrintAnimals(rats);
             * PrintRats(rats);
             * PrintRats(animals);
             *
             * Why??
             */
        }
Example #2
0
        public static void Main(string[] args)
        {
            // Suppose I have a few collections of animals.
            Iguana[] igs     = new Iguana[] { new Iguana() };
            Rat[]    rats    = new Rat[] { new Rat() };
            Animal[] animals = new Animal[] { new Iguana(), new Rat() };

            // Which of these function calls is valid?

            /*
             * PrintAnimal(igs[0]);
             * PrintAnimal(animals[0]);
             * PrintIguana(animals[0]);
             * PrintRat(igs[0]);
             * PrintRat(rats[0]);
             *
             * Why??
             */

            // How about these?

            /*
             * PrintAnimals(animals);
             * PrintAnimals(igs);
             * PrintAnimals(rats);
             * PrintRats(rats);
             * PrintRats(animals);
             *
             * Why??
             */


            /* And these???
             * Action<Animal> a2 = PrintAnimal;
             * Action<Rat> a2 = PrintRat;
             *
             * Action<Iguana> a1 = PrintAnimal;
             * Action<Rat> a1 = PrintAnimal;
             * Action<Animal> a2 = PrintRat;
             */


            /* Or THESE???
             * Func<Rat> f1 = CreateRat;
             * Func<Iguana> f2 = CreateRat;
             * Func<Animal> f3 = CreateRat;
             *
             */

            // CONCLUSIONS:

            // A collection can be covariant if it is ____________________.
            // A collection can be contravariant if it is ____________________.


            // A function pointer/delegate can be covariant in its ________________.
            // A function pointer/delegate can be contravariant in its ________________.
        }
Example #3
0
 public static void PrintIguana(Iguana a)
 {
     Console.WriteLine(a.Speak());
 }