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.
Yes - the difference between
ref
andout
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 useref
instead. Usually the calling code looks like this:Now if we used
ref
, we'd have to givevalue
a value before the call, e.g.: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:In this case
ok
andvalue
would be implicitly typed tobool
andint
respectively. That way it's clear what's going into the method (text
) and what's coming out (two pieces of information:ok
andvalue
).That would simply not be available if
int.TryParse
used aref
parameter instead - as the compiler can't know whether it's going to actually care about the initial value of theref
parameter.