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






using System; 
 
class Swap { 
  // This method now changes its arguments. 
  public void swap(ref int a, ref int b) { 
    int t; 
  
    t = a; 
    a = b; 
    b = t; 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    Swap ob = new Swap(); 
 
    int x = 10, y = 20; 
 
    Console.WriteLine("x and y before call: " + x + " " + y); 
 
    ob.swap(ref x, ref y);  
 
    Console.WriteLine("x and y after call: " + x + " " + y); 
  } 
}
x and y before call: 10 20
x and y after call: 20 10








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