I feel my question is pretty dumb, or another way to put it is : I’m too lost in my code to see a workaround for now. Stay too long on a problem, and your vision becomes narrower and narrower ><. Plus I’m not good enough with inheritance, polymorphism and so
Here is the idea : I have multiple list of derived class, and I would like to call generic functions on those lists (accesing and modifying members of the base class). I feel there is something to do with inheritance, but I don’t manage to make it work as I want for now .
Here is a very simple example of what I’m intending to do :
class Baseclass
{
public int ID;
public string Name;
}
class DerivedClass1 : Baseclass
{
}
private void FuncOnBase(List<Baseclass> _collection)
{
// ...
foreach (Baseclass obj in _collection)
{
++obj.ID;
}
// ...
}
private void FuncTest()
{
List<DerivedClass1> collection1 = new List<DerivedClass1>();
collection1.Add(new DerivedClass1() { ID = 1 });
collection1.Add(new DerivedClass1() { ID = 2 });
collection1.Add(new DerivedClass1() { ID = 3 });
FuncOnBase(collection1); // ==> forbidden, cannot convert the derived class list to the base class list
}
Gotta love variance. A
List<DerivedClass1>is not aList<Baseclass>– otherwise,FuncOnBasecould attempt to add aBaseclassto the list, and the compiler wouldn’t spot it.One trick is to use a generic method:
In terms of the example I presented above – note that we are able to add a
Tto the list; useful in particular if we add theT : new()constraint, or pass in (for example) aparams T[].Note also that
IEnumerable<T>becomes covariant in C# 4.0 / .NET 4.0, so if you passed in just anIEnumerable<Baseclass>(rather than a list) it would work “as is”: