Can't contravariance be solved with interfaces?

Posted by Sir Psycho on Stack Overflow See other posts from Stack Overflow or by Sir Psycho
Published on 2010-04-23T01:56:04Z Indexed on 2010/04/23 2:03 UTC
Read the original article Hit count: 389

Filed under:
|

Hi,

I'm at the point where I'm starting to grasp contravariance, although I'm trying to work out what the advantage is when an interface can be used instead. Obviously I'm missing something.

Here is the c#4 example

class Dog : Animal {
        public Dog(string name) : base(name) { }
    }

    class Animal {

        string _name;

        public Animal(string name) {
            _name = name;
        }

        public void Walk() {
            Console.WriteLine(_name + " is walking");
        }
    }

 Action<Animal> MakeItMove = (ani) => { ani.Walk(); };

            Action<Dog> MakeItWalk = MakeItMove;

            MakeItWalk(new Dog("Sandy"));

Same example which works in earlier versions on c#

class Dog : Animal {
        public Dog(string name) : base(name) { }
    }

    class Animal : IAnimal {

        string _name;

        public Animal(string name) {
            _name = name;
        }

        public void Walk() {
            Console.WriteLine(_name + " is walking");
        }
    }

    interface IAnimal {

        void Walk();
    }

    Action<IAnimal> MakeItMove = (ani) => { ani.Walk(); };

                Action<IAnimal> MakeItWalk = MakeItMove;

                MakeItWalk(new Dog("Sandy"));

These may not be the best examples, but I still can't seem to 'get it'. Is the in keywork defined on the action delegate simply a short hand syntax way like lamda is to delegates?

© Stack Overflow or respective owner

Related posts about c#

Related posts about contravariance