What is ref keyword in C#: Explanation and Examples
ref keyword in C# allows a method to receive a reference to a variable instead of a copy, so changes inside the method affect the original variable. It is used to pass arguments by reference, enabling the method to modify the caller's data directly.How It Works
Imagine you have a piece of paper with a number written on it. Normally, if you give a copy of that paper to a friend, they can change their copy but your original stays the same. Using ref is like giving your friend the original paper instead of a copy. Any changes they make will be on your original paper.
In C#, when you pass a variable to a method without ref, the method gets a copy of the value. But with ref, the method gets a reference to the original variable's memory location. This means the method can change the variable's value, and the change will be visible outside the method.
This is useful when you want a method to update multiple values or when copying large data would be inefficient.
Example
This example shows how ref lets a method change the original variable's value.
using System; class Program { static void Increment(ref int number) { number = number + 1; } static void Main() { int value = 5; Console.WriteLine($"Before: {value}"); Increment(ref value); Console.WriteLine($"After: {value}"); } }
When to Use
Use ref when you want a method to modify the caller's variable directly. This is helpful when:
- You need to update multiple values inside a method.
- You want to avoid copying large structs or data for performance reasons.
- You want to return more than one value from a method without using tuples or out parameters.
For example, in game development, you might want to update a player's position or health directly inside a method. Or in calculations, you might want to adjust parameters without creating new copies.
Key Points
refpasses variables by reference, not by value.- The variable must be initialized before passing it with
ref. - Both the method definition and call must use the
refkeyword. refdiffers fromoutbecauseoutvariables don't need to be initialized before passing.- Using
refcan improve performance by avoiding copies of large data.
Key Takeaways
ref keyword passes variables by reference, allowing methods to modify the original variable.ref must be initialized before the method call.ref keyword to work.ref is useful for updating multiple values or improving performance by avoiding copies.ref differs from out in initialization requirements and usage.