What is pass by value and Pass by reference in C#?

Solution

We can call a method then there are two ways to pass arguments to the calling method.

  • Pass by Value
  • Pass by Reference

By default C# uses pass by value approach by calling a method.

Pass by Value

By default when we call a method in C# and pass parameter in that method, C# compiler creates a new copy of each variable that is passed into the method. So, any changes that we make in the method parameters will apply only in that parameter itself inside the scope of the method.

Consider the below example

 class Program
   {
        static void Main(string[] args)
        {
            int number = 10;

            IncrementNumber(number);
            Console.WriteLine($"Value of number in Main method ={number}");

            Console.ReadLine();
        }

        static void IncrementNumber(int num)
        {
            num+=15;
            Console.WriteLine($"Value of num inside Increment Number ={num}");
        }
   }

Output

Value of num inside Increment Number =25
Value of number in Main method =10;

In the above example when we call the IncrementNumber (num) method by passing number variable then C# compiler creates a new copy of num variable and copies the value inside number variable into num argument variable. After this, it does not matter, how many changes we make in num variable it does not affect the value stored in the number variable. This behaviour is known as pass by value and is default in C#.

Pass By Ref

Pass by reference is another type to pass parameter in a method. C# provides ref keyword for passing arguments by reference in a method.

Consider the below example

   class Program
   {
        static void Main(string[] args)
        {
            int number = 10;

            IncrementNumber(ref number);
            Console.WriteLine($"Value of number in Main method ={number}");

            Console.ReadLine();
        }

        static void IncrementNumber(ref int num)
        {
            num+=15;
            Console.WriteLine($"Value of num inside Increment Number ={num}");
        } 
  }

Output

Value of num inside Increment Number =25
Value of number in Main method =25;

In the above example when we call the IncrementNumber (num) method by passing number variable by reference, then C# compiler will pass the reference of number variable and copies the reference of number variable into num argument variable. So both number and num are pointing to the same memory location. After this, If we make any change in through the number or num variable it will be reflected in both variable as both pointing to the same memory address. This behaviour is known as pass by reference in C#.

Note: In the above example we have used C# string interpolation ("${}") syntax to format string. Which is new feature of C# 6.0. Refer here to explore more new features of C# 6.0

Share this thread

Comments

Comments
comments powered by Disqus

Navigation

Social Media