Monday, March 2, 2026

Difference Between ref and out keywords in C#

Both ref and out are used to pass arguments by reference in C#.

That means the method can modify the original variable value.


1. ref Keyword

  • Variable must be initialized before passing

  • Used when method reads and modifies the value

  • Memory must already contain a value

Example

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

int x = 5;
AddTen(ref x);
// x becomes 15

2. out Keyword

  • Variable does NOT need initialization before passing

  • Method must assign a value before returning

  • Used mainly for returning multiple values

Example

void GetNumber(out int number)
{
    number = 20;
}

int x;
GetNumber(out x);
// x becomes 20

Key Differences (List Format)

  1. Initialization

    • ref → Must initialize before passing

    • out → No need to initialize before passing

  2. Value Assignment Inside Method

    • ref → Optional to assign

    • out → Mandatory to assign

  3. Usage Purpose

    • ref → Modify existing value

    • out → Return value from method

  4. Memory

    • Both pass variable reference (same memory location)


Simple Rule to Remember

  • If variable already has value → use ref

  • If method will create and return value → use out