Mixer
Mixer

Reputation: 1332

How to pass various derived classes of the same interface within a generic List as a parameter to the function?

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);
        }

    }

Upvotes: 3

Views: 1240

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501606

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:

    void Calculate(IEnumerable<ControlPoint> points)

This will use generic covariance.

2) You could make the method generic:

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

I would prefer the first in general - and even if you're not using .NET 4 / C# 4, if you can change Calculate to use IEnumerable<T> instead of List<T>, that would be cleaner - so you could mix the two and have a generic method taking IEnumerable<T>.

Upvotes: 8

Related Questions