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
refandoutis in terms of definite assignment:An
outparameter 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
refparameter 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 userefinstead. Usually the calling code looks like this:Now if we used
ref, we'd have to givevaluea 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
outparameter 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
outparameter 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
okandvaluewould be implicitly typed toboolandintrespectively. That way it's clear what's going into the method (text) and what's coming out (two pieces of information:okandvalue).That would simply not be available if
int.TryParseused arefparameter instead - as the compiler can't know whether it's going to actually care about the initial value of therefparameter.