Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing things with objects as if they were parents

Tags:

c#

inheritance

The following code give me an error saying that there are invalid arguments in my call of doStuffToLines(segments)

Shouldn't I be able to do this since I have my DimensionLineSegment inherits from Lines?

    private void doStuff()
    {
        List<DimensionLineSegment> segments = new List<DimensionLineSegment>();

        doStuffToLines(segments);

    }

    private void doStuffToLines(List<Line> lines)
    {

    }
like image 280
General Ackbar Avatar asked Jun 12 '14 21:06

General Ackbar


1 Answers

You can't pass a concrete type to the method because List is not covariant.

You can try something like this:

public void doStuffToLines<T>(IList<T> lines) where T : Line
{
  //do some thing           
}

By specifying a generic constraint, you can limit the generic type passed to a object of type Line or it's derived descendants.

One thing to note, is if you're using .NET 4.0, you could potentially change your method from accepting List to IEnumerable because the T generic parameter is covariant.

like image 160
Michael G Avatar answered Oct 08 '22 04:10

Michael G