Difference between Ref and Out keywords in C#

Here is the difference between Ref and Out keywords in C#:

The main difference between ref and out is that ref requires the argument to be initialized before it is passed to the called method, while out does not. ref keyword is generally used when the called method needs to both read and write the value of the argument, while out keyword is typically used when the called method only needs to write to the argument and the calling method is responsible for initializing it.

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

What is Ref Keyword in C#?

The ref keyword is used to pass an argument by reference. This means that the called method can modify the value of the argument and the changes will be reflected in the calling method. The argument must be initialized before it is passed to the called method.

  • The ref keyword must be used in the declaration of both the calling method and the called method.
  • The argument must be initialized before it is passed to the called method using the ref keyword.
  • The called method can both read and write the value of the argument.
  • The ref keyword allows parameters to be passed as references, meaning that any changes made to the variables within the called method will be reflected in the original variables in the calling method.

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

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

In the output shown above, it is clear that the modifications made to the variable number in the called method have been reflected in the calling method.

What is Out Keyword in C#?

The out keyword allows you to pass parameters to a method as reference types, regardless of whether they have been assigned a value or not. It functions similarly to the ref keyword. However, it is required that the value of a parameter be initialized in the called method before control is returned to the calling method.

  • Normally, a method can only return a single value. However, the out keyword can be used to enable a method to return multiple values.
  • If you want to pass a variable as an out parameter to a method, you do not need to initialize it before passing it as an out parameter.
  • When using the out keyword, it is necessary to initialize the parameter within the called method.

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 2:

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.

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

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.

C# ref vs out comparison

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

Comparisonref keywordout keyword
Definition:Passes a reference to the memory location of a variablePasses a reference to a new memory location that is created when the function is called
Initialization:The caller must initialize the value of the parameter before calling the function.
Example:
int number = 10;
SomeMethod(ref number);
The caller does not need to initialize the value of the parameter before calling the function.
Example:
int number;
SomeMethod(out number);
Value types:Can be used with value types.Can only be used with value types.
Reference types:Can be used with reference types.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:Must be usedMust be used
Use in a function call:Must be usedMust not be used
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:There is no constraint. The ref parameter may or may not be re-initialized by the called method.The called method must initialize the parameter passed as 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 passing a value type as a reference (using either the ref or out keyword), there is no boxing of the value. Instead, only the reference to the value is passed. This is in contrast to passing by value, where the actual value of the variable is passed.

This means that when passing a value type as a reference, changes made to the value within the called function will be reflected in the calling code, whereas changes made to a value type passed by the value will not be reflected in the calling code.

Ref and out keywords in method overloading

In C#, it is not possible to use the ref and out keywords simultaneously in method overloading. Specifically, it is not possible to overload a method by having one version of the method take a ref parameter and another version take 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# 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.

The ref should be used when the value is known before calling the method; out should be used when the value is unknown before calling the method.

FAQ

Here are some common questions about the ref and out keywords in C#, along with their answers:

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