26 August 2013

Pass By Value and Pass By Reference in C#

In C#, when argument is passed by value, the called method receives the copy of the variable value while argument is passed by reference the called method receives only reference not value. 
In the case of Pass by value in C# called method cannot change the received variable value because it receives value. In the case of Pass by reference the called method can change the received variable value because it receives reference and in the case of pass of pass by reference only one copy of variable value is maintained, only references are passed to called methods. But in the case of pass by value the number of copy variable value is depend on the number of called methods, that means if there are five called methods then there are five copies are maintained. 
Pass By Value in C#:
using System;

namespace CSharpPassByValueReference 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            int j = 10; 
            Console.WriteLine("Before Pass By Value: " + j.ToString()); 
            Display(j); 
            Console.WriteLine("After Pass By Value: " + j.ToString());  
            Console.ReadLine();   
        } 

        private static void Display(int i) 
        { 
            i = 20;               
        } 
    } 
}

As shown above, we are passing the arguments to the Display() method by value and the output is as shown below. 

As output shown, the value of the passed variable is same before and after calling the method in the case of pass by value. 
Pass By Reference in C#: 
using System;
namespace CSharpPassByValueReference 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            int j = 10; 
            Console.WriteLine("Before Pass By Value: " + j.ToString()); 
            Display(ref j); 
            Console.WriteLine("After Pass By Value: " + j.ToString());  
            Console.ReadLine();  
        }

        private static void Display(ref int i) 
        { 
            i = 20;               
        } 
    } 
}

As shown above, we are passing the arguments to the Display() method by ref and the output is as shown below. 
  
As output shown, the value of the passed variable is different before and after calling the method in the case of pass by reference.