I have two classes: a base class (Animal) and a class deriving from
it (Cat).Base class contains one virtual method Play that takes List as input parameter.Something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication9
{
class Animal
{
public virtual void Play(List<Animal> animal) { }
}
class Cat : Animal
{
public override void Play(List<Animal> animal)
{
}
}
class Program
{
static void Main(string[] args)
{
Cat cat = new Cat();
cat.Play(new List<Cat>());
}
}
}
When i compile the above program,i get the following error
Error 2 Argument 1: cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.List'
Is there anyway to accomplish this?
The reason you cannot do this is because a list is writable. Suppose it were legal, and see what goes wrong:
Well dog my cats, that is badness.
The feature you want is called “generic covariance” and it is supported in C# 4 for interfaces that are known to be safe.
IEnumerable<T>does not have any way to write to the sequence, so it is safe.That will work in C# 4 because
List<Cat>is convertible toIEnumerable<Cat>, which is convertible toIEnumerable<Animal>. There is no way that Play can useIEnumerable<Animal>to add a dog to something that is actually a list of cats.