Sobes.tech
Junior

What are the ref and out keywords in C#?

sobes.tech AI

Answer from AI

ref passes the argument by reference. Changes made to the parameter inside the method are reflected on the original variable. The variable must be initialized before passing it to the method.

out also passes the argument by reference, but is used for returning values. The variable does not need to be initialized before passing it to the method. The method must assign a value to the out parameter before it finishes.

// Example of using ref
void IncrementRef(ref int number)
{
    number++; // Changes the original variable
}

int a = 5;
IncrementRef(ref a); // a now equals 6

// Example of using out
void GetCoordinates(out int x, out int y)
{
    x = 10; // Must assign a value
    y = 20; // Must assign a value
}

int coordX, coordY; // No need to initialize
GetCoordinates(out coordX, out coordY); // coordX = 10, coordY = 20