How to create a common class with inheritance?

How can I do the following code? I don’t think I understand C # generics completely. Maybe someone can point me in the right direction.

public abstract class A { } public class B : A { } public class C : A { } public static List<C> GetCList() { return new List<C>(); } static void Main(string[] args) { List<A> listA = new List<A>(); listA.Add(new B()); listA.Add(new C()); // Compiler cannot implicitly convert List<A> listB = new List<B>(); // Compiler cannot implicitly convert List<A> listC = GetCList(); // However, copying each element is fine // It has something to do with generics (I think) List<B> listD = new List<B>(); foreach (B b in listD) { listB.Add(b); } } 

This is probably the simple answer.

Update: Firstly, this is not possible in C # 3.0, but it is possible in C # 4.0.

To run it in C # 3.0, which is just a workaround until 4.0, use the following:

  // Compiler is happy List<A> listB = new List<B>().OfType<A>().ToList(); // Compiler is happy List<A> listC = GetCList().OfType<A>().ToList(); 
+1
source share
2 answers

you can always do it

 List<A> testme = new List<B>().OfType<A>().ToList(); 

As noted by Boyan Resnik, you can also do ...

 List<A> testme = new List<B>().Cast<A>().ToList(); 

The difference is that Cast <T> () will not work if one or more of the types do not match. WhereType <T> () will return an IEnumerable <T> containing only objects that are convertible

+3
source

The reason this does not work is because it cannot be determined that it is safe. Suppose you have

 List<Giraffe> giraffes = new List<Giraffe>(); List<Animal> animals = giraffes; // suppose this were legal. // animals is now a reference to a list of giraffes, // but the type system doesn't know that. // You can put a turtle into a list of animals... animals.Add(new Turtle()); 

And hey, you just put the turtle on the list of giraffes, and now the integrity of the system has been violated. That is why it is illegal.

The key point here is that “animals” and “giraffes” belong to ONE OBJECT, and this object is a list of giraffes. But the list of giraffes cannot do as much as the list of animals can do; in particular, it cannot contain a turtle.

+4
source

All Articles