How to pass a List with different inherited classes to the function takes the parent interface List?
The compiler generates an error.
public interface ControlPoint
{
}
public class Knot: ControlPoint
{
}
public class Node: ControlPoint
{
}
class Spline
{
List<Knot> knots=new List<Knot>();
List<Node> nodes=new List<Node>();
void Calculate(List<ControlPoint> points) {} //<------- Compiler Error
void Test()
{
Calculate(knots);
Calculate(nodes);
}
}
Two options:
1) If you’re using C# 4 and .NET 4+, and you only need to iterate over the points in
Calculate, just change the signature to:This will use generic covariance.
2) You could make the method generic:
I would prefer the first in general – and even if you’re not using .NET 4 / C# 4, if you can change
Calculateto useIEnumerable<T>instead ofList<T>, that would be cleaner – so you could mix the two and have a generic method takingIEnumerable<T>.