Tuesday, June 11, 2013

Call by value and Call by reference in C#

Call by value and call by reference is not a new concept of C#. Those who started their programming life with C and C++ like me they are pretty well aware of this concept. And here again let’s talk again this concept .

Call by value:-

public static class TestClass

    {
        public static void ShowData(int a)
        {
            a = 200;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int a = 100;
            TestClass.ShowData(a);
            Console.WriteLine(a);
            Console.ReadLine();
        }
    }


Here within main function I have created one integer variable(a) . And set value 100. Then i have passed the value of a through of  TestClass.ShowData(a); function. Now when sending this value to another function called ShowData() , then the copy of this value is going to this function. And then I am changing the value of a within this function.(i=200). Again I am showing value of a within Main() function.
And the value is still 100 though I have re-initialize within ShowData() function.
Now, Why the value is not getting change ? Because I did not send actual address of the variable but value of the variable. And the variable which I have created within ShowData() function is completely different than the variable of main function.

Call by Reference:-

Call by reference is opposite than call by Value. In call by reference we will send address of variable rather than the value of variable. For example

public static class TestClass
    {
        public static void Change(ref int a)
        {
            Console.WriteLine("Value in Change Function:- "+ a);
            a = 200;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int a = 100;
            TestClass.Change(ref a);
            Console.WriteLine("Value in Main function:- "+ a);
            Console.ReadLine();
        }
    }


Here from main function I am sending reference or address of variable a to Change() function. And when I am creating variable within Change() function , I am taking reference of a variable. And now both a variable are pointing to same address.
And basically when I am re assigning it within Change() function , My variable within Main() function is getting reflected.
And this is call by reference.
Hope you have understood this concept.


No comments:

Post a Comment