Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what situations are 'out' parameters useful (where 'ref' couldn't be used instead)?

As far as I can tell, the only use for out parameters is that a caller can obtain multiple return values from a single method invocation. But we can also obtain multiple result values using ref parameters instead!

So are there other situations where out parameters could prove useful and where we couldn't use ref parameters instead?

Thank you.

like image 340
flockofcode Avatar asked Jun 27 '10 19:06

flockofcode


1 Answers

Yes - the difference between ref and out is in terms of definite assignment:

  • An out parameter doesn't have to be definitely assigned by the caller before the method call. It does have to be definitely assigned in the method before it returns normally (i.e. without an exception). The variable is then definitely assigned in the caller after the call.

  • A ref parameter does have to be definitely assigned by the caller before the method call. It doesn't have to be assigned a different value in the method.

So suppose we wanted to change int.TryParse(string, out int) to use ref instead. Usually the calling code looks like this:

int value;
if (int.TryParse(text, out value))
{
    // Use value
}
else
{
    // Do something else
}

Now if we used ref, we'd have to give value a value before the call, e.g.:

int value = 0;
if (int.TryParse(text, ref value))
{
    // Use value
}
else
{
    // Do something else
}

Obviously it's not a huge difference - but it gives the wrong impression. We're assigning a value that we have no intention of ever using, and that's not a good thing for readability. An out parameter indicates that a value will come out of the method (assuming there's no exception) and that you don't need to have a value to start with.

Once of the suggestions I've made for C# 5 (I've no idea if it'll be taken up or not) is that a method with an out parameter should be able to regarded as a method returning a tuple of values. Combined with better support for tuples, that would mean we could do something like this:

var (ok, value) = int.TryParse(text);

In this case ok and value would be implicitly typed to bool and int respectively. That way it's clear what's going into the method (text) and what's coming out (two pieces of information: ok and value).

That would simply not be available if int.TryParse used a ref parameter instead - as the compiler can't know whether it's going to actually care about the initial value of the ref parameter.

like image 191
Jon Skeet Avatar answered Nov 10 '22 02:11

Jon Skeet