C# ref vs. out: What’s the Difference?

Ibrahim Jaber
2 min readApr 29

In C#, both the ref and out keywords are used for passing parameters by reference. However, there are some differences between the two that are important to understand.

When you pass a parameter by value, the function gets a copy of the parameter’s value. Any changes made to the parameter inside the function do not affect the original value of the parameter. However, when you pass a parameter by reference, the function gets a reference to the original parameter’s memory location. Any changes made to the parameter inside the function will affect the original value of the parameter.

The ref keyword is used to pass a parameter by reference, but the parameter must be initialized before it is passed. The out keyword, on the other hand, is used to declare that a parameter is an output parameter, which means that the parameter does not need to be initialized before it is passed. Instead, the function is responsible for initializing the output parameter.

Here’s an example that demonstrates the use of ref and out in C#:

class Program
{
static void Main(string[] args)
{
int x = 5;
int y;

// Call the function with a parameter passed by reference
AddOne(ref x);
Console.WriteLine("x after AddOne(ref x): " + x);

// Call the function with an output parameter
MultiplyByTwo(3, out y);
Console.WriteLine("y after MultiplyByTwo(3, out y): " + y);
}

static void AddOne(ref int num)
{
num += 1;
}

static void MultiplyByTwo(int num, out int result)
{
result = num * 2;
}
}

In the above example, we first initialize the variable x to the value 5. We then call the function AddOne and pass x by reference using the ref keyword. The AddOne function adds 1 to the value of x, so when we print the value of x after the function call, we see that it is now 6.

Next, we call the function MultiplyByTwo and pass 3 as the first parameter. We also declare a variable y and pass it as the second parameter using the out keyword. The MultiplyByTwo function multiplies the first parameter by 2 and assigns the result to the result parameter, which is y in our case. When we print the value of y after the function call, we see that it is 6, which is the result of multiplying 3 by 2.

In summary, ref and out are useful keywords in C# for passing parameters by reference. While ref is used to pass a parameter that is already initialized, out is used to declare an output parameter that does not need to be initialized before it is passed.

--

--

Ibrahim Jaber

Software developer | Programming and Blockchain enthusiast