C# Passing Parameter by Reference

C#First of all, you need to understand each and every variable has its own memory location.  Normally, whenever you pass a parameter while calling a function, you pass it by its value.  As a result, a new variable will be created at a new location without affecting the original variable.

In other situation, when you pass the variable by its reference, the called function will directly affect the original variable.  You must use ref keyword before type of the variable while calling that function and also when you assign type of parameter of that particular function.

To understand this logic, please go through the example given below and compare the output.

 

Passing by Value:

using System;

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

            function(num);
            Console.WriteLine(num);
        }

        public static void function(int num)
        {
            num = 30;
        }
    }
}

Output:

10
Press any key to continue . . .

 

Passing By Reference:

using System;

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

            function(ref num);
            Console.WriteLine(num);
        }

        public static void function(ref int num)
        {
            num = 30;
        }
    }
}

 Output:

30
Press any key to continue . . .