EasyConcept

What is the difference between ref and out parameters in C#?

Technology:
C#
Experience:
Junior,
Mid-level

Quick answer

Both pass an argument by reference, but ref requires the variable to be initialised before the call, while out requires the method to assign a value before it returns.

Detailed explanation

Use ref when the method both reads and modifies the caller's variable. Use out when the method only produces a value, such as the bool TryParse(string, out int result) pattern, which lets a method return a success flag and a value together. A third modifier, in, passes by reference as read-only, useful to avoid copying large structs.

In modern C# you can often return a tuple instead ((bool ok, int value)), which is clearer than out parameters.

Example

csharp
if (int.TryParse(input, out int number))
{
    Console.WriteLine(number * 2);
}

static void AddTen(ref int x) => x += 10;
int n = 5;
AddTen(ref n);          // n is now 15
  • C#Medium

    What is LINQ in C# and what is deferred execution?

    LINQ (Language Integrated Query) lets you query collections, databases and XML with a consistent syntax, and deferred execution means a query does not run when you define it but when you enumerate the results.

    Junior 路 Mid-level 路 Functions & Scope
  • C#Easy

    What is the difference between string and StringBuilder in C#?

    A string is immutable, so every change creates a new string object, while StringBuilder is a mutable buffer that modifies its contents in place, making it much faster for repeated concatenation.

    Intern 路 Junior 路 Performance
  • C#Easy

    What is the difference between const and readonly in C#?

    A const is a compile-time constant that must be assigned where it is declared, while a readonly field can be assigned at declaration or in the constructor, so its value can be decided at runtime.

    Junior 路 Mid-level 路 Programming Fundamentals