Wednesday, June 4, 2025

πŸ’‘ ref, out, and in in C# – What’s the Difference and When to Use






Published on: June 4, 2025

Category: Code Snippet/Tip Day

Tags: C#, ref keyword, out keyword, in keyword, .NET Tips, C# Parameters, .NET Dev Corner




🧠 What are ref, out, and in?

Keyword Behavior Requirement Use Case
ref Passes a reference; can read & write Must be initialized before passing Modify the input and return a result
out Outputs a value from a method Does not need to be initialized before Return multiple values from a method
in Read-only reference Must be initialized before passing Pass large structs without copying


πŸ” ref Example

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

int myValue = 5;
AddTen(ref myValue);
Console.WriteLine(myValue); // Output: 15



πŸ” out Example

bool TryDivide(int dividend, int divisor, out int result)
{
    if (divisor == 0)
    {
        result = 0;
        return false;
    }
    result = dividend / divisor;
    return true;
}

int answer;
if (TryDivide(10, 2, out answer))
    Console.WriteLine($"Result: {answer}"); // Output: 5


πŸ” in Example

void PrintPoint(in Point p)
{
    Console.WriteLine($"X: {p.X}, Y: {p.Y}");
}

readonly struct Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y) => (X, Y) = (x, y);
}

var point = new Point(5, 10);
PrintPoint(in point);


πŸ“Œ Summary Table

Use This When You Need To…
ref Modify a parameter and retain changes
out Return a value via parameter (often alongside return)
in Pass read-only struct efficiently


🧠 Pro Tip

  • Avoid excessive use of ref and out in public APIs—use tuples or objects instead.
  • Use in with large value types to improve performance.



πŸ“¬ Stay Connected