C# Interview Question #86

What are ref, out, and in parameters in C#?

Advanced C# Language Features Mid-Level Intermediate

Quick Interview Answer

ref, out, and in pass arguments by reference rather than passing the parameter value normally.

Detailed Explanation

ref, out, and in pass arguments by reference rather than passing the parameter value normally.

ref allows a method to read and modify an existing variable. The caller must initialize it before the call.

out is used when the method is expected to assign a value. The caller does not need to initialize the variable first, but the called method must assign it before returning.

in passes an argument by readonly reference. It can help avoid copying larger value types while preventing reassignment through the parameter.

These features should be used when they improve the API clearly; returning values or tuples is often easier to understand for ordinary application code.

Code Example

void Increment(ref int value)
{
    value++;
}

bool TryParseAge(string text, out int age)
{
    return int.TryParse(text, out age);
}

void Print(in DateTime date)
{
    Console.WriteLine(date);
}