Sunday, June 8, 2025

๐Ÿงช Understanding the Difference Between ref, out, and in in C#






Published on: June 8, 2025
Category: C# Fundamentals
Tags: CSharp, ref, out, in, Parameters in C#, Interview Questions, .NET Dev Corner, Pass by Reference, Coding Tips, .NET




๐Ÿ”น Introduction

In C#, parameters can be passed to methods in multiple ways: by value, by reference, and with modifiers like ref, out, and in. Understanding the differences between these is crucial for clean, predictable code — and it’s a favorite topic in interviews!



๐Ÿ”ง ref Keyword

  • Purpose: Allows the method to read and modify the original value of the argument.
  • Requirement: Variable must be initialized before being passed.
  • Usage:

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

int myNumber = 5;
UpdateValue(ref myNumber); // myNumber becomes 15


๐Ÿ“ค out Keyword

  • Purpose: Used when a method needs to return multiple values.
  • Requirement: Variable doesn’t need to be initialized before the method call, but must be assigned inside the method.
  • Usage:
void GetValues(out int x, out int y)
{
    x = 10;
    y = 20;
}

int a, b;
GetValues(out a, out b); // a = 10, b = 20


๐Ÿ”’ in Keyword (Introduced in C# 7.2)

  • Purpose: Passes arguments by reference but as read-only — ideal for performance with large structs.
  • Requirement: Variable must be initialized and cannot be changed inside the method.
  • Usage:
void Display(in int value)
{
    Console.WriteLine(value);
    // value++; // ❌ Compile-time error
}

int readOnlyValue = 50;
Display(in readOnlyValue);


⚖️ Summary Table

Feature ref out in (C# 7.2+)
Initialization before call ✅ Required ❌ Not required ✅ Required
Assignment inside method Optional ✅ Required ❌ Not allowed
Read-only access ❌ No ❌ No ✅ Yes
Best used for Modify input Return multiple values Performance with large structs


๐Ÿ“Œ Use Cases in Real Projects

  • Use ref when modifying a value like a counter or buffer size.
  • Use out to return values from parsing operations (int.TryParse).
  • Use in when passing large readonly data (e.g., ReadOnlySpan<T> or big structs) for performance.


๐Ÿง  Final Thoughts

Understanding the behavioral differences of ref, out, and in helps in:

  • Writing performance-optimized C# code
  • Avoiding unintended side effects
  • Cracking .NET and C# technical interviews with confidence



๐Ÿ“ฌ Stay Connected