Ref and Out in C#

Understanding the difference between ref and out keywords in C#

Yohan Malshika
3 min readOct 31, 2024
Ref and Out in C#

In C#, ref and out are keywords used to pass arguments by reference to a method. They allow a method to change a variable's value and pass to it. But there are some differences between ref and out keywords. Let’s discuss these two keywords more.

The ref Keyword

The ref keyword allows a method to modify the value of a variable passed to it. However, the variable must be initialized (given a value) before passing it to the method.

How ref Works

  • The variable must be initialized before passing it to a method with ref.
  • The method can modify the variable's value, and this change will also be reflected outside the method.

Example :

using System;

class Program
{
static void Main()
{
int number = 10; // Must initialize before using ref
Console.WriteLine($"Before: {number}"); // Outputs: Before: 10

ModifyWithRef(ref number);

Console.WriteLine($"After: {number}"); // Outputs: After: 20
}

static void ModifyWithRef(ref int value)
{
value = value * 2; // Change the value to 20
}
}

--

--