Swap メソッド

値を Swap するメソッドです。

using System;

class Program {
    static void Swap<T>(ref T a, ref T b) {
        var t = a;
        a = b;
        b = t;
    }

    static void Main() {
        int a = 1;
        int b = 2;
        Console.WriteLine($"{a} {b}");
        Swap(ref a, ref b);
        Console.WriteLine($"{a} {b}");

        var xs = new[] { 3, 4 };
        Console.WriteLine($"{xs[0]} {xs[1]}");
        Swap(ref xs[0], ref xs[1]);
        Console.WriteLine($"{xs[0]} {xs[1]}");
    }
}

実行結果です。

1 2
2 1
3 4
4 3