Skip to main content
Published on

ref and out in C#

Share:

Introduction

In programming, we frequently encounter situations where we need a method to return more than one value or directly modify the arguments provided. In C#, ref and out are two essential modifiers that offer this capability. However, each has its own particularities that deserve attention.

Pass by Value vs. Pass by Reference

Before we dive deeper into ref and out, it is crucial to understand the difference between pass by value and pass by reference.

  • Pass by Value: A copy of the value is passed to the method. Modifications to this value do not affect the original.
  • Pass by Reference: A reference to the original variable is passed. Modifications directly affect the original value.

Unwrapping ref

The ref modifier indicates that an argument is passed by reference, not by value.

Characteristics of ref:

  • The variable must be initialised before being passed.
  • Changes made inside the method are reflected outside it.

Exploring out

The out modifier is similar to ref in that it passes arguments by reference.

Characteristics of out:

  • The variable does not need to be initialised before being passed.
  • The variable must be initialised inside the method before the method returns.
using System;

namespace Base {
  class RefAndOut {
    public void Run() {
      int number1 = 0, number2;

      Ref(ref number1);
      Out(out number2);

      Console.WriteLine($"Value after Ref method: {number1}");   // 2
      Console.WriteLine($"Value after Out method: {number2}");   // 3
    }

    void Ref(ref int num) {
      num = 2;
    }

    void Out(out int num) {
      num = 3;
    }
  }
}

When to use ref or out?

Both ref and out have their applications:

  • Use ref when you expect the argument to have already been initialised and the method to modify that value.
  • Use out when you want the method to be responsible for initialising or setting the value.

Conclusion

Both ref and out are valuable tools in C# that offer greater flexibility when manipulating data between methods. By understanding their characteristics and differences, you will be better equipped to use these modifiers effectively in your projects.

Happy coding!