3

Can you write a swap routine for generic lists covariantly? Here is a swap routine which won't work:

public static void Swap(List<IComparable> list, int pos1, int pos2)
{
    IComparable temp = list[pos1];
    list[pos1] = list[pos2];
    list[pos2] = temp;
}

Calling Swap(new List<int>{1,2}, 0, 1) won't work here because this version of Swap isn't covariant.

Darrell Plank
  • 1,124
  • 7
  • 5
  • 5
    It will be much easier to understand what are you talking about if you add some sample code, even pseudo code. – Konrad Kokosa Jan 08 '14 at 23:44
  • Wall of text and no code. I'm too lazy to read all that. – Federico Berasategui Jan 08 '14 at 23:52
  • 3
    @HighCore Not every programming problem is about code. Get used to it. – poke Jan 08 '14 at 23:54
  • For those not familiar with covariant vs invarient http://stackoverflow.com/questions/18666710/why-are-arrays-covariant-but-generics-are-invariant and http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p/2745301#2745301 – John Sobolewski Jan 08 '14 at 23:54
  • @DarrellPlank Please edit your question instead of posting code as a comment. – poke Jan 08 '14 at 23:54
  • @poke that doesn't make me less lazy. BTW it would be nice to see what the OP is really trying to do. Whatever it is I'm pretty sure it can be solved with 1 line of LINQ or the like – Federico Berasategui Jan 08 '14 at 23:56
  • @poke - sorry - haven't used StackOverflow that much. Thanks for the hint! – Darrell Plank Jan 09 '14 at 00:30

1 Answers1

3

Does this work for you?

public static void Swap<T>(this List<T> list, int pos1, int pos2)
{
    T tmp = list[pos1];
    list[pos1] = list[pos2];
    list[pos2] = tmp;

}

This allows you to specify the type and make the swap possible.

John Sobolewski
  • 4,512
  • 1
  • 20
  • 26
  • Great answer, jsobo. Dumb of me not to recognize it. Will be better prepared the next time this comes up! Thanks again! – Darrell Plank Jan 09 '14 at 00:47