C# – What is an Out Parameter and Why Use It

c++

Why do we use ouput parameters, e.g.

void f() {
    int first, next;
    read(out first, out next);
}

void read (out int first, out intnext) {
    first = console.read();
    next = console.read();
}

Instead of writing all this code why don’t we use:

void f() {
    int first, next;
    first = console.read();
    next = console.read();
}

Best Answer

An out parameter is very much like having an extra return value.

It's rarely a good idea to have an out parameter in a method which has a void return type, like the example you gave... but sometimes you want to be able to return multiple values at a time. Even in your example, you might want to encapsulate the "I'm reading from the console twice" idea in a single method call. It's somewhat unlikely in this case, because the operations are so easily separable - but in other cases, performing some work naturally gives two bits of information, and you don't want to have to repeat the work to get both bits. You could encapsulate them in a new struct or class, of course, but sometimes that's just a pain.

With .NET 4, it would often be a better idea to return a Tuple<...> instead, mind you. So whereas int.TryParse has a signature of

bool TryParse(string text, out int value)

it might have been better as

Tuple<bool, int> TryParse(string text)
Related Question