Difference between Ref and Out keywords in C#

The main difference between ref and out keyword is that ref requires the variable to be initialized before being passed to the method, whereas out does not. Additionally, out enforces that the variable must assign a value inside the method.

C# ref and out keywords
C# ref and out keywords

C# Ref vs Out

In C#, both the ref and out keywords are used to pass arguments to methods by reference instead of by value. However, there is a slight difference between them.

Ref keyword:

The ref keyword is used to pass an argument by reference. That means It allows the called method to change the argument’s value, and these changes will reflect in the original variable in the calling method. However, it’s important to initialize the variable before passing it to the method.

  • When using ref, the variable being passed must be initialized before being passed to the method.
  • It allows two-way communication between the method and the calling code. Any changes made to the parameter inside the method will be reflected in the calling code.
  • The method can access the value of the variable passed in, but it doesn’t have to assign a new value to it.

Out keyword:

In C#, the out keyword is used to pass arguments to a method by reference.

We use the out keyword when we want a method to return multiple values. By using out keyword, we can pass variables to the method that are initially uninitialized, and the method is responsible for assigning values to those variables before it completes execution. 

  • When using out, the variable being passed does not need to be initialized before being passed to the method.
  • It also allows two-way communication between the method and the calling code, similar to ref.
  • However, the method must assign a new value to the parameter inside the method before it returns. The variable passed in as out must be assigned a value inside the method, or it will result in a compilation error.
using System;

public class Program
{
    static void Main()
    {
        int x = 5;
        int y = 10;

        // Using ref keyword
        Console.WriteLine("Using ref keyword:");
        Console.WriteLine("Before method call: x = " + x);
        MultiplyByTwo(ref x);
        Console.WriteLine("After method call: x = " + x);
        Console.WriteLine();

        // Using out keyword
        Console.WriteLine("Using out keyword:");
        int result;
        MultiplyByThree(out y, out result);
        Console.WriteLine("After method call: y = " + y + ", result = " + result);
    }

    // Method that multiplies the parameter by two using ref keyword
    static void MultiplyByTwo(ref int number)
    {
        // The method doesn't have to assign a new value to 'number'
        // We can modify the existing value
        number *= 2;
        // The change made to 'number' is reflected in the calling code
    }

    // Method that multiplies the parameter by three using out keyword
    static void MultiplyByThree(out int number, out int result)
    {
        number = 3;
        result = number * 2;
       // Both 'number' and 'result' are assigned inside the method
    }
}

Output:

Using ref keyword:
Before method call: x = 5
After method call: x = 10

Using out keyword:
After method call: y = 3, result = 6

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

Example 2: ref keyword in C#

The following example demonstrates the use of the ref keyword to pass value-type parameters to a 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.

The result indicates that the modifications made to the “number” variable in the called method have been updated in the calling method as well.

Example: Out keyword 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.

Example 3: Passing multiple out parameters to a method.

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.

It is not possible to pass a property as a ref or out parameter, because properties are implemented as methods, not variables.


In C#, a method typically returns only one data type at a time. However, by using the out parameters, a method can return multiple values of different data types simultaneously.

C# ref vs out comparison

Here is a comparison of the ref and out keywords in C#:

Comparisonref keywordout keyword
Definition:The ref keyword allows passing a reference to a variable, enabling the called method to modify its value, and the changes are reflected in the calling code.The out keyword enables passing variables to a method without requiring initialization, and the method assigns values to these variables later on. It allows multiple values to be returned from the method.
Initialization:The caller must initialize the value of the ref parameter before calling the function.
Example:
int number = 10;
SomeMethod(ref number);
The caller does not need to initialize the value of the out parameter before calling the function.
Example:
int number;
SomeMethod(out number);
Value types:ref can be used with value types.out can only be used with value types.
Reference types:ref can be used with reference types.out cannot be used with reference types.
Modification:The function can both read and modify the value of the parameter, and the changes will be reflected in the calling code.The function can modify the value of the parameter, and the changes will be reflected in the calling code
Use in a function definition:ref must be used in the function definition.It also must be used in the function definition.
Use in a function call:ref must be used when calling a function.out must not be used when calling the function.
Direction:When the ref keyword is used, data can flow in bi-directions. The out keyword is used to get data in a one-way mode.
Return value:Usually, the ref keyword is not used to return multiple values from a method.The out keyword is useful when a function needs to return multiple values.
Constraint:No constraint. The ref parameter may or may not be re-initialized by the called method.he called method must initialize the parameter passed as the out keyword.
Declaration:Use ref when you know the value at the time of declaration.Use out when you don’t know the value at the time of declaration.
Difference between ref and out keyword in C#

When you pass a value type as a reference using ref or out, only a reference to the value is passed, so changes made to the value in the called function affect the original value in the calling code.

However, when you pass a value type by value, the actual value is passed, so changes made in the called function won’t affect the original value in the calling code.

Ref and out keywords in method overloading

In C#, you cannot use the ref and out keywords at the same time when overloading methods. This means you cannot have one version of a method that takes a ref parameter and another version that takes an 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 C# when one version of the method takes a ref argument and another version takes a normal argument. In this case, the method can be called with either a ref argument or a normal argument, depending on the needs of the calling code.

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#, the ref and out keywords are used to pass arguments as a reference to a method. If you use ref or out, any changes made to the argument inside the method will affect the original value outside the method.

When you know the value before calling the method, use ref. But when you don’t know the value before calling the method, use out.

FAQs

Here are some common questions about the ref and out keywords in C#:

Q: Is it possible to use a property of a class as ref or out parameters?

Properties are not variables. They are methods, thus they can’t be used as ref or out parameters.

Q: How do you use ref and out parameters?

Both the out and ref keywords are used to pass arguments to a method as a reference type, but the out keyword is generally used when a method has to return multiple values, whereas the ref keyword is typically used when an existing variable is to be modified in a method.

Q: Are functions ref type in C#?

By default, the value type variable is passed by value, while the reference type variable is passed by reference from one method to another method in C#.
The keywords ref and out in C# allow us to pass value type variables to another method by the reference.

Q: Can you use the ref keyword with a value type?

A: Yes, you can use the ref keyword with value types such as integers, float, long, structures, etc.

Q: Can you use the out keyword with a reference type?

A: No, the out keyword can only be used with value types, not reference types.

Q: Can we return multiple values from a function using the ref keyword?

A: Yes, we can use the ref keyword to return multiple values from a function. However, it is more common to use the out keyword for this purpose, as the out keyword is specifically designed for returning multiple values through its parameters.

Related post:  Value type and Reference type in C#

I hope this post was helpful. If you have any questions, please feel free to leave them in the comments section below.

Recommended Articles

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments