C#: Good/best implementation of Swap method

前端 未结 6 1488
醉话见心
醉话见心 2020-12-06 10:33

I read this post about card shuffling and in many shuffling and sorting algorithms you need to swap two items in a list or array. But what does a good and efficient Swap met

6条回答
  •  佛祖请我去吃肉
    2020-12-06 11:17

    For anyone wondering, swapping can also be done also with Extension methods (.NET 3.0 and newer).

    In general there seems not to be possibility to say that extension methods "this" value is ref, so you need to return it and override the old value.

    public static class GeneralExtensions {
        public static T SwapWith(this T current, ref T other) {
            T tmpOther = other;
            other = current;
            return tmpOther;
        }
    }
    

    This extension method can be then used like this:

    int val1 = 10;
    int val2 = 20;    
    val1 = val1.SwapWith(ref val2);
    

提交回复
热议问题