2

I have a class, which implements this simple interface:

public interface IPosition
{
    int? Position { get; set; }
}

And I have a class to resort collection of classes by this Position property:

public static class ReorderPositions
{
    public static IList<IPosition> Reorder(IList<IPosition> list)
    {
        // different actions, resorting
        return positionList;
    }
}

So, for testing it I create fake class (other properties are not necessary for me of real class for reordering):

public class ReorderPositionsFakeModel : IPosition
{
    public int? Position { get; set; }
}

Then I created a factory class to fill List<ReorderPositionsFakeModel>:

    public static class ReorderPositionFakeModelFactory
    {
        public static IList<ReorderPositionsFakeModel> Create(List<int> positions)
        {
            positions = positions.OrderBy(x => x).ToList();
            List<ReorderPositionsFakeModel> model = new();
            foreach (var position in positions)
            {
                model.Add(new ReorderPositionsFakeModel { Position = position });
            }
            return model;
        }
    }

but when I try to use:

var model = ReorderPositionFakeModelFactory.Create(new List<int> { -2, -1, 0, 4, 5, 6, 7, 9, 10, 11, 12, 18, 19, 20, 21, 23, 24, 25, 26 });
var result = ReorderPositions.Reorder(model);

I got:

Error CS1503 Argument 1: cannot convert from 'System.Collections.Generic.IList<ReorderPositionsFakeModel>' to 'System.Collections.Generic.IList<IPosition>'

why so? What is wrong? ReorderPositionsFakeModel implements IPosition, why can't be converted?...

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Oleg Sh
  • 8,496
  • 17
  • 89
  • 159

2 Answers2

3

The issue you're facing is due to the fact that you're trying to pass a list of ReorderPositionsFakeModel objects to the ReorderPositions. Reorder method that expects a list of IPosition objects. Try this:

var model = ReorderPositionFakeModelFactory.Create(new List<int> { -2, -1, 0, 4, 5, 6, 7, 9, 10, 11, 12, 18, 19, 20, 21, 23, 24, 25, 26 });
var result = ReorderPositions.Reorder(model.Cast<IPosition>().ToList());
Byte
  • 143
  • 10
1

IList<ReorderPositionsFakeModel> is not IList<IPosition> (for example you can add IPosition to the latter, but not to the former). There are several ways to handle this. One is to use covariant IEnumerable<out T> interface instead of IList:

public static class ReorderPositions
{
    public static IEnumerable<IPosition> Reorder(IEnumerable<IPosition> list)
    {
        // different actions, resorting
        return default;
    }
}

public static class ReorderPositionFakeModelFactory
{
    public static IEnumerable<ReorderPositionsFakeModel> Create(List<int> positions)
    {
        // ...
    }
}

Or create new list with the required type:

ReorderPositions.Reorder(model.ToList<IPosition>());
Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
Guru Stron
  • 102,774
  • 10
  • 95
  • 132