Sobes.tech
Junior — Middle

What is the difference between using the ref keyword and out in passing arguments in C# methods?

sobes.tech AI

Answer from AI

In C#, the keywords ref and out are used for passing arguments by reference but have different semantics:

  • ref requires the variable to be initialized before passing it to the method. The method can read and modify its value.
  • out does not require the variable to be initialized beforehand, but the method must assign it a value before it returns.

Example:

void MethodRef(ref int x) {
    x = x + 1; // can read and modify
}

void MethodOut(out int y) {
    y = 10; // must assign a value
}

int a = 5;
MethodRef(ref a); // a must be initialized

int b; // not initialized
MethodOut(out b); // method must assign b

Summary:

  • ref — for passing already initialized variables; the method can read and modify them.
  • out — for returning values from a method via parameters; the variable does not need to be initialized before the call.