Difference between Ref and Out keywords in C#

The ref and Out keywords in C# are used to pass parameters as reference. Out keyword does the same thing as the ref, but it doesn’t require the caller to assign a value before calling the function.

C# ref keyword

Ref parameter in C#: If you want to pass a variable as a ref parameter, you must initialize it before passing it as a reference parameter to the method. The ref keyword is used to pass parameters as references, which means that any change in the values ​​of the variables in the method will be reflected in the original variables 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 use the ref keyword to pass value type parameters to the method.

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 ++;
        }
    }
}


image- output of ref keyword in C# program
The output of the above program.

In the above output, we can see that the changes we made to the variable number in the called method have been reflected in the calling method.

c# out keyword

Out parameters in C#: If you want to pass a variable as an out parameter, you don’t need to initialize it before passing it as an out parameter to the method.

The out keyword is used to pass parameters to the method as reference type, regardless of whether they are assigned a value or not. It is similar to the ref keyword.

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

By default, a method can only return one value, but when we want a method to return multiple values, we can use the  out  keyword.

Example of the out parameter in C#.

Let’s take a look at the following example of using out parameter in C#.

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;
        }
    }
}



image- out keyword output
Result of the above c# program.

Passing multiple out parameters.

The following is a simple example of using out parameters to return multiple values ​​of different data types.

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 only return one data type at a time but using out parameters, a method can return multiple values ​​of different data types.

ref and out keywords in C#

Here are the key points about the ref and out keywords in C#

ref keyword in C#

      • If we use the ref parameter, we must initialize the value of the variable before passing it as a parameter to the method.
      • ref keyword state that the parameter passed may be modified by the called method.
      • In the case of ref parameters, the data can be bidirectional.
      • Use ref when you know the value at the time of declaration.

out keyword in C#

      • 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 keywords in method overloading

In C# we can’t use ref and out keywords 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 keywords in C# 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.
The following example 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#

In case you have any doubt, please post your feedback, question, or comments.

Thanks for visiting.

Recommended Articles

    1. 10 Difference between interface and abstract class In C#
    2. IEnumerable Interface in C# with examples
    3. Constructors in C# with Examples
    4. C# Enum | How To Play With Enum in C#?
    5. Exception Handling in C#| Use of try, catch and finally block
    6. Generic Delegates in C# With Examples
    7. C# Dictionary with Examples
    8. Multithreading in C#

Leave a Reply