Difference Between Ref and Out Keywords in C#

In this blog, I am going to explain the difference between Ref and Out Keywords in C#. This detailed blog will cover the following topics as follows

  1. Introduction
  2. Reference Parameters in C#
  3. What is the ref in C#?
    • Key Points
  4. What is out in C#?
    • Key Points
  5. Bonus Concept 
    • Method Overloading with Ref and Out Keywords
  6. Similarities between Ref and Out keywords in C#
  7. Difference between Ref and Out keywords in C#
  8. Conclusion

Reference Parameters in C#

As per Microsoft, "You apply one of the following modifiers to a parameter declaration to pass arguments by reference instead of by value":

  • ref: The argument must be initialized before calling the method. The method can assign a new value to the parameter but isn't required to do so.
  • out: The calling method isn't required to initialize the argument before calling the method. The method must assign a value to the parameter.
  • ref readonly: The argument must be initialized before calling the method. The method can't assign a new value to the parameter. 
  • in: The argument must be initialized before calling the method. The method can't assign a new value to the parameter. The compiler might create a temporary variable to hold a copy of the argument to in parameters.

Ref Keyword in C#

The ref keyword in C# is used to pass arguments by reference. In simple words, any changes made to this argument in the method will be reflected in that variable when the control returns back to the calling method.

Key Points

  • An argument for a ref parameter must include the ref modifier/keyword.
  • Data can pass bi-directionally when the ref keyword is used.
  • Ref means the method can read or write the value of the argument.
  • Properties cannot be arguments to ref parameters since they are variables, not methods.

Examples

The example given in this section demonstrates the functionality of Ref Keyword in C#. Let's see.

namespace RefVsOutInCsharp.RefKeyword
{
    internal class RefInCsharp
    {
        static void Main(string[] args)
        {
            int originalValue = 10;
            Console.WriteLine("-- Example of Ref Keyword In C# --");
            Console.WriteLine("Original Ref value: " + originalValue);
            DoubleValue(ref originalValue);
            Console.WriteLine("New Ref value: " + originalValue);

            Console.ReadLine();
        }

        static void DoubleValue(ref int value)
        {
            value *= 2;
        }
    }
}

Output

Out Keyword in C#

Out keyword in C# is used to pass arguments by reference. Declaring parameters for out method is useful when multiple values need to be returned from the method.

Key Points

  • An argument for an out parameter must include the out modifier/keyword.
  • Out means the method sets the value of the argument.
  • When out keyword is used, then data is passed in a unidirectional way only.
  • Properties cannot be arguments to out parameters since they are variables, not methods.

Examples

The example given in this section demonstrates the functionality of Out Keyword in C#. Let's see.

namespace RefVsOutInCsharp.OutKeyword
{
    internal class OutInCsharp
    {
        static void Main(string[] args)
        {
            int area, perimeter;

            CalculateDimensions(100, 200, out area, out perimeter);
            Console.WriteLine("-- Example of Out Keyword In C# --");
            Console.WriteLine("Area: " + area);
            Console.WriteLine("Perimeter: " + perimeter);

            Console.ReadLine();
        }

        static void CalculateDimensions(int width, int height, out int area, out int perimeter)
        {
            area = width * height;
            perimeter = 2 * (width + height);
        }
    }
}

Output

Bonus Concept: Method Overloading with Ref and Out Keywords

According to Microsoft, “Member overloading means creating two or more members on the same type that differ only in the number or type of parameters but have the same name”. But, when you apply method overloading with ref and out keywords, it will behave differently. As both ref and out keywords are treated differently at run time and at compile time, they are treated the same.

Example

namespace RefVsOutInCsharp.MethodOverloadingWithRefAndOut
{
    class MethodOverloadingWithRefAndOut
    {
        public static void Main(string[] args)
        {
            int id = 0;
            MethodOverloadingWithRefAndOutInCSharp(ref id);
            MethodOverloadingWithRefAndOutInCSharp(out id);
        }

        public static string MethodOverloadingWithRefAndOutInCSharp(ref int id)
        {
            Console.WriteLine(id);
            id += 1;
            return "Ref";
        }

        public static string MethodOverloadingWithRefAndOutInCSharp(out int id)
        {
            id = 0;
            Console.WriteLine(id);
            return "Out";
        }
    }
}

Output

Ref and Out keywords code example in C#

Similarities between Ref and Out keywords in C#

  • Both ref and out parameters pass the arguments by reference instead of by value.
  • Both keywords can be used with any data type (value types and reference types).
  • Both ref and out parameters are treated the same at compile time but differently at runtime.
  • The ref and out keywords must be specified explicitly in both the method definition and the calling method.
  • Properties cannot be passed as out or ref parameters because properties are not variables; they are methods.
  • The async method can't declare ref or out parameters, nor can it have a reference return value, but it can call methods that have such parameters.

Difference between Ref and Out keywords in C#

The following example will show you both the Ref and Out keywords working together in C#.

namespace RefVsOutInCsharp.RefVsOut
{
    internal class RefVsOut
    {
        public static void refMethod(ref int value1)
        {
            value1 = 11;
        }
        public static void outMethod(out int value2)
        {
            value2 = 10;  // Must be assigned before exiting the method
        }
        public static void Main()
        {
            int val1 = 9;   //must be initialized 
            int val2;       //optional

            Console.WriteLine("-- Difference between Ref and Out Keywords in C# --");

            refMethod(ref val1);
            Console.WriteLine("Ref value is: {0}", val1);

            outMethod(out val2);
            Console.WriteLine("Out value is: {0}", val2);

            Console.ReadLine();
        }
    }
}

Output

The ref and out keywords in C# are often confusing for beginners and experienced alike, but they serve different purposes. Now, let's look at the quick difference between ref and out keywords in C#.

S. No Key Points Ref Keyword Out Keyword
1 Definition The ref keyword in C# is used to pass arguments by reference. Out keyword in C# is used to pass arguments by reference.
2 strong>Direction Data can pass bi-directionally when the ref keyword is used. When out keyword is used, then data is passed in a unidirectional way only (from the called method to the caller method).
3 Initialization An argument that is passed to a ref parameter must be initialized before it's passed.

 

Variables passed as out arguments don't have to be initialized before being passed in a method call.
4 Usage Passing parameter values ?? by ref is useful when the called method also needs to modify the value of the passed parameter. Declaring parameters for out method is useful when multiple values ?? need to be returned from the method.

See you in the next blog, till then, take care and be happy learning.

You can connect with me @

Reference: https://learn.microsoft.com/

Conclusion

In this blog, we have discussed the difference between Ref and Out Keywords/Parameters in C#.

I hope you enjoyed this blog. Follow C# Corner to learn more new and amazing things about C#.

Thanks for reading.

 

Next Recommended Reading Ref And Out KeyWords In C#