Difference between Ref and Out keywords in C#

Introduction

In C# ref and out keywords are basically used to pass arguments as a reference within a method.

With the ref keyword, we have the choice to not make changes to the parameter inside the called method. Whereas using the out keyword, we must initialize the parameter inside the called method.

Ref keyword

The ref keyword in C# is used to pass an argument as a reference. That means any changes to the variable value inside the method will get reflected in the original variable in the calling method.

In C# ref keyword returns the address of the variable rather than the value.

C# passing parameter by reference

In the following example, we are passing a value type parameter to a method by using ref.

using System;
namespace Ref
{
    class program
    {
        public static void Main()
        {
            // Calling method

            int number = 10; // Variable must be initialized.

            Console.WriteLine($"Previous value of the number = {number}");

            //Passing int number as ref parameter in the method

            PassByReference(ref number);

            Console.WriteLine($"Current value of the number = {number}");

            Console.ReadLine();
        }
        public static void PassByReference(ref int number)
        {
            //Called method
            number ++;
        }
    }
}


The output of the above program.

In the above result, we can see that the changes that we did for the variable ‘number’ in the called method have reflected in the calling method.

Out keyword

The out  keyword is used to pass arguments to the method as a reference type with or without assigning any value to it. It is similar to the ref keyword.

Using out, It is mandatory to initialize the value of a parameter in the called method before control returns to the calling method.

We can use the out keyword when we want a method to return multiple values.

Example of the out parameter.

using System;
namespace OutKeyword
{
    class program
    {
        public static void Main()
        {
            //Calling method

            int number; // Initialization is optional

            OutMethod(out number);

            Console.WriteLine($"number:{number} after passed to the called method");

            Console.ReadKey();
        }

        public static void OutMethod(out int number)
        { 
            //Called method
            number = 20;
        }
    }
}



Result of the above c# program.

Passing multiple out parameters.

Example to return multiple values of different data types using out

using System;
namespace OutKeyword
{
    class program
    {
        public static void Main()
        {
            // Calling method
           
            int id;  // Initialization is optional in case of out parameter
            string name;

            OutMethod(out id, out name);

            Console.WriteLine($"Id : {id} , Name = {name}");

            Console.ReadKey();
        }
        public static void OutMethod(out int id, out string name)
        {
            //Called method

            //Return multiple values using out parameters
            id = 52894;

            name = "Shekh Ali";
        }
    }
}
The output of the above program:
The output of the above program.

We know that In C#, a method can return only one data type at a time. Using out parameter a method can return multiple values of different data types.

ref vs out parameter

ref

      • It is mandatory to initialize the variable value before we pass it as an argument to the method.
      • ref keyword state that the parameter passed may be modified by the called method.
      • Data can be bidirectional in the case of ref.
      • Use ref when you know the value at the time of declaration.

out

      • It is not mandatory to initialize the value of a parameter before passing to the called method.
      • Using out keyword, you must initialize the parameter inside the called method.
      • With out keyword data can be unidirectional, Data will pass from called to calling method only.
      • Use out when you don’t know the value at the time of declaration.
      • The out keyword is useful when a function needs to return multiple values.
      • There might be a scenario when we want the method itself to initialize the parameter, we can do this with the out keyword.

Note: We can’t pass a property as a ref or out parameter since internally they are method not variable.

There is no boxing of a value type when we pass it as a reference. In the case of pass by value, the value of the variable is passed whereas for the ref and out only the reference is passed.

Ref and out keyword in method overloading

In C# we can’t use ref and out in method overloading simultaneously.
Methods overloading is not possible in case one method takes a ref parameter and the other method out parameter.

Ref and out in method overloading
The above two methods are identical in terms of compilation.

Method overloading is possible in case one method takes a ref argument and the other method takes a normal argument.
We can see in the following example which is perfectly valid for the method overloading.

using System;
namespace MethodOverLoading
{
    class program
    {   
        public static void MyMethod(int a)
        {           
            a = 10;          
        }
        public static void MyMethod(out int b)
        {   
            //method signature must be different.      
            b = 10;
        }
    }
}

Summary

In C# both ref and out keywords are used to pass arguments as a reference within a method.
Any changes in the variable value inside the method will get reflected outside the calling method.

In my previous post i have explained about the Value type and Reference type in C#

Hope you enjoyed this post. Thanks for visiting.

Leave a Reply

Your email address will not be published. Required fields are marked *

twelve − 3 =