Tool for HR, Hiring Managers, and the Leadership Team

Why do we use ref, out, and in keywords?

In C#, ref, out, and in keywords are used to pass parameters by reference instead of by value.

This means the method works directly on the original variable, not a copy.

🔹 Why Do We Use Them?

Normally in C#, parameters are passed by value (copy is created).

But sometimes we want to:

  • Return multiple values

  • Modify original variable

  • Avoid copying large objects (performance)

That's when we use:

  • ref

  • out

  • in

🔹 1. ref Keyword

ref passes variable by reference

  • Must initialize before passing

  • Can read and modify value

Example

public void Increase(ref int number)
{
    number = number + 10;
}

int num = 5;
Increase(ref num);

Console.WriteLine(num); // 15

👉 Original value changed

🔹 2. out Keyword

out is used to return multiple values

  • No need to initialize before passing

  • Must assign value inside method

Example

public void GetValues(out int a, out int b)
{
    a = 10;
    b = 20;
}

int x, y;
GetValues(out x, out y);

Console.WriteLine(x); // 10
Console.WriteLine(y); // 20

👉 Used for multiple return values

🔹 3. in Keyword

in passes variable by reference but read-only

  • Cannot modify value

  • Improves performance for large objects

Example

public void Display(in int number)
{
    Console.WriteLine(number);
}

int num = 10;
Display(in num);

❌ This will cause error:

number = 20; // Not allowed

🔹 Difference Between ref, out, in

Feature ref out in
Must initialize before passing ✅ Yes ❌ No ✅ Yes
Must assign inside method ❌ No ✅ Yes ❌ No
Can modify value ✅ Yes ✅ Yes ❌ No
Pass by reference ✅ Yes ✅ Yes ✅ Yes

🔹 Real World Example

Using out (TryParse)

int number;
bool result = int.TryParse("123", out number);

Here:

  • Method returns bool

  • Number returned via out

🔹 Interview One-Line Answer 

  • ref → Pass by reference (read & modify)

  • out → Return multiple values

  • in → Pass by reference (read-only)

🔹 Interview Trick Question

Can we use ref without initializing?

❌ No

Can we use out without initializing?

✅ Yes

🔹 When to Use What

  • Use ref → When modifying existing value

  • Use out → When returning multiple values

  • Use in → For performance (large structs)