Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting List<> of Derived class to List<> of base class

Tags:

c#

generics

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?

like image 762
santosh singh Avatar asked Sep 15 '10 18:09

santosh singh


4 Answers

The reason you cannot do this is because a list is writable. Suppose it were legal, and see what goes wrong:

List<Cat> cats = new List<Cat>();
List<Animal> animals = cats; // Trouble brewing...
animals.Add(new Dog()); // hey, we just added a dog to a list of cats...
cats[0].Speak(); // Woof!

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.

class Animal    
{    
    public virtual void Play(IEnumerable<Animal> animals) { }    
}    
class Cat : Animal    
{    
    public override void Play(IEnumerable<Animal> animals) { }    
}    
class Program    
{    
    static void Main()    
    {    
        Cat cat = new Cat();    
        cat.Play(new List<Cat>());    
    }    
}  

That will work in C# 4 because List<Cat> is convertible to IEnumerable<Cat>, which is convertible to IEnumerable<Animal>. There is no way that Play can use IEnumerable<Animal> to add a dog to something that is actually a list of cats.

like image 140
Eric Lippert Avatar answered Nov 18 '22 19:11

Eric Lippert


You could do a few things. One example is cast the elements of the list to Animal

Using your code:

cat.Play(new List<Cat>().Cast<Animal>().ToList());

Another is to make Animal generic, so cat.Play(new List<Cat>()); would work.

class Animal<T>
{
    public virtual void Play(List<T> animals) { }
}
class Cat : Animal<Cat>
{
    public override void Play(List<Cat> cats)
    {
    }
}

class Program
{
    static void Main(string[] args)
    {
        Cat cat = new Cat();
        cat.Play(new List<Cat>());
    }
}

One other method is to not make Animal generic, but the Play method and constrain that to T : Animal

class Animal
{
    public virtual void Play<T>(List<T> animals) where T : Animal { }
}
class Cat : Animal
{
    public override void Play<T>(List<T> animals) 
    {
    }
}

Finally, if you are on C# 4 and only need to enumerate over the list and not modify it, check Eric Lippert's answer on IEnumerable<Animal>.

like image 36
Anthony Pegram Avatar answered Nov 18 '22 18:11

Anthony Pegram


You're looking for generic collection covariance. Obviously, though, that feature is not supported by the version of C# that you're using.

You can work around it by using the Cast<T>() extension method. Be aware, though, that this will create a copy of your original list instead of passing the original as a different type:

cat.Play((new List<Cat>()).Cast<Animal>().ToList());
like image 12
Justin Niessner Avatar answered Nov 18 '22 20:11

Justin Niessner


use the extension method Cast()

so:

class Program
{
    static void Main(string[] args)
    {
        Cat cat = new Cat();
        cat.Play(new List<Cat>().Cast<Animal>());
    }
}

The reason for this is b/c .net 3.5 does not support covariance, but 4.0 does :)

like image 3
Jose Avatar answered Nov 18 '22 20:11

Jose