Can't contravariance be solved with interfaces?
- by Sir Psycho
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?