Sobes.tech
Junior — Middle

Millised on erinevused võtmesõnade ref ja out vahel, kui edastate viidatud muutujad meetodites?

sobes.tech AI

Vastus AI-lt

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

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

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; // not initialized
ExampleOut(out b); // method assigns a value to b

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