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.

Main Method: a = 10 | v AddFive(ref a) | v x (points to same notebook as a) Inside AddFive: x = x + 5 --> now notebook says 15

When the method finishes:

  • Both x (inside method) and a (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.

Main Method: b = (blank) | v SetToTen(out b) | v y (points to same notebook as b) Inside SetToTen: y = 10 --> method writes value into notebook

When the method finishes:

  • Both y (inside method) and b (in Main) point to the same notebook.

  • Value = 10


🧠 Easy Visualization

ref → 📓 (already has notes, method can read & change them) out → 📒 (blank, method must write before giving it back)

Comments

Popular posts from this blog

.NET Core Interview Questions and Answers for 10+ Years Experienced Professionals

What are SOLID Principles?

.NET Core Senior Interview Q&A