How can I pass different derived classes of the same interface to a shared list as a function parameter?

How can I pass a list with different inherited classes to a function that takes the parent List interface? 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);
        }

    }

      

+3


source to share


1 answer


Two options:

1) If you are using C # 4 and .NET 4+ and you only need to iterate over the dots in Calculate

, just change the signature to:

    void Calculate(IEnumerable<ControlPoint> points)

      

This will use common covariance.



2) You can do a generic method:

    void Calculate<T>(List<T> points) where T : ControlPoint

      

I'd prefer the former in general - and even if you're not using .NET 4 / C # 4, if you can change Calculate

to use IEnumerable<T>

instead List<T>

, it will be cleaner - so you can mix them up and use the common method IEnumerable<T>

.

+8


source







All Articles