Swap two references. : ref « Language Basics « C# / CSharp Tutorial






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








1.11.ref
1.11.1.Use ref to pass a value type by reference
1.11.2.Swap two values
1.11.3.Swap two references.
1.11.4.Use out for reference type
1.11.5.Use ref for int value
1.11.6.Use ref for reference type
1.11.7.Change string using ref keyword
1.11.8.Passing Parameters by Value