What is the difference between ref and out keywords?
Difference between ref and out keywords
🔹 Both ref and out
-
Are used to pass variables by reference (not by value).
-
That means the method can change the original variable’s value.
🔹 Difference in simple words
| Feature | ref |
out |
|---|---|---|
| Initialization before method call | Variable must be initialized before you pass it. | Variable doesn’t need to be initialized before passing. |
| Use inside method | Method can read and write the value. | Method must assign a value before the method ends. |
| Think like | You’re giving a notebook that already has something written inside. | You’re giving a blank notebook, the method must write something before returning it. |
🔹 Example
using System;
class Program
{
static void Main()
{
int a = 10; // initialized
int b; // not initialized
AddFive(ref a); // a must have a value
SetToTen(out b); // b doesn’t need a value before
Console.WriteLine("a = " + a); // Output: 15
Console.WriteLine("b = " + b); // Output: 10
}
🔹 Super Simple Memory Trick
-
ref = reference with value already given
-
out = output will be given by method
static void AddFive(ref int x)
{
x = x + 5; // can read and modify
}
static void SetToTen(out int y)
{
y = 10; // must assign before returning
}
}
Great 👍 Let’s make a step-by-step memory picture of how ref and out behave.
1️⃣ With ref
Imagine you already have a notebook 📓 with something written in it (a = 10).
You give it to the method.
When the method finishes:
-
Both
x(inside method) anda(in Main) point to the same notebook. -
Value = 15
2️⃣ With out
Here, you give the method an empty notebook 📒 (no value needed).
The method must write something before returning.
When the method finishes:
-
Both
y(inside method) andb(in Main) point to the same notebook. -
Value = 10
🧠 Easy Visualization
Comments
Post a Comment