Mega Code Archive

 
Categories / C# Tutorial / Language Basics
 

Swap two references

using System;    class RefSwap {    int a, b;        public RefSwap(int i, int j) {      a = i;      b = j;    }      public void show() {      Console.WriteLine("a: {0}, b: {1}", a, b);    }      // This method changes its arguments.    public void swap(ref RefSwap ob1, ref RefSwap ob2) {      RefSwap t;         t = ob1;      ob1 = ob2;      ob2 = t;    }  }    class MainClass {    public static void Main() {      RefSwap x = new RefSwap(1, 2);      RefSwap y = new RefSwap(3, 4);        Console.Write("x before call: ");      x.show();        Console.Write("y before call: ");      y.show();        Console.WriteLine();        // exchange the objects to which x and y refer      x.swap(ref x, ref y);         Console.Write("x after call: ");      x.show();        Console.Write("y after call: ");      y.show();      }  } x before call: a: 1, b: 2 y before call: a: 3, b: 4 x after call: a: 3, b: 4 y after call: a: 1, b: 2