Sobes.tech
Junior — Middle

What are the differences between the keywords ref and out when passing reference variables in methods?

sobes.tech AI

Answer from AI

In C#, the keywords ref and out are used for passing parameters by reference but have important differences:

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

Example:

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

void ExampleOut(out int y) {
    y = 42; // must assign
}

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

int b; // uninitialized
ExampleOut(out b); // method assigns value to b

Thus, ref is used when you want to pass and modify an existing value, while out is used when the method needs to return multiple values via parameters.