Darrell Plank
Darrell Plank

Reputation: 1164

Swapping two elements in a list covariantly

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.

Upvotes: 3

Views: 866

Answers (1)

John Sobolewski
John Sobolewski

Reputation: 4572

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.

Upvotes: 3

Related Questions