Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections with generic objects

There is a method that takes a list of base objects as a parameter.

abstract class Base {}
class MyClass:Base {}
//...
void Method(List<Base> list) {}

When I`m calling that method, I want to pass list of derived objects.

var derivedList = new List<MyClass>();
Method(derivedList);

But I cannot do that because collection of derived is not the same as collection of base objects. What is the best practice to handle this situation? Now I'm using my extension .ToBase() where I create new collection, but I think there is nicer solution.

Thanks.

like image 954
Vladimir Nani Avatar asked Feb 14 '11 13:02

Vladimir Nani


1 Answers

Make your Method generic:

public void Method<T>(List<T> list) where T : Base
{
    //Do your stuff
}
like image 136
Klaus Byskov Pedersen Avatar answered Sep 23 '22 08:09

Klaus Byskov Pedersen