Workaround for creating a generic list of Type and populate it with derived classes?

If I understand what you are trying to do, you should be able to do it just fine List myList = new List(); SubClass item1 = new SubClass(); SuperClass item2 = new SuperClass(); myList. Add(item1); myList. Add(item2) This is valid code, and then you can easily retrieve the elements from the list, and use the basic rules of polymorphism for changing the types of the objects accordingly.

If I understand what you are trying to do, you should be able to do it just fine. List myList = new List(); SubClass item1 = new SubClass(); SuperClass item2 = new SuperClass(); myList. Add(item1); myList.

Add(item2); This is valid code, and then you can easily retrieve the elements from the list, and use the basic rules of polymorphism for changing the types of the objects accordingly.

That would work fine. While you won't know the exact type of an item in the list (without casting) there are no problems with adding a derived type to a collection of base types. What the article links to is the case where you try to use a collection of derived types as a collection of base types: void DisplayFruit(List fruit) { fruit.

ForEach(f => Console. WriteLine(f.ToString())); } List apples = new List(); // add apples here DisplayFruit(apples); //Error! If apples were declared as a List instead, it would work.

As Brian notes, this should work fine. The only common limitation people see in this area is covariance of lists as method arguments - i.e. They find that they can't pass a List to a method that accepts a List.

The answer in that case is generics: public void Foo(IList list) where T : Animal {...} .... List dogs = ... Foo(dogs); // implicit For more discussion on covariance (including the C# 4.0 changes that doesn't change the above scenario, see here).

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions