Swap two references : Parameters Passing : Language Basics C# Source Code


Custom Search

C# Source Code » Language Basics » Parameters Passing »

 

Swap two references









    

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// 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 now changes its arguments. 
  public void swap(ref RefSwap ob1, ref RefSwap ob2) { 
    RefSwap t; 
  
    t = ob1; 
    ob1 = ob2; 
    ob2 = t; 
  } 
} 
 
public class RefSwapDemo { 
  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(); 
 
  } 
} 


           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Language Basics
» Parameters Passing