More on the out method parameter

I’m sure this is boring for about 99% of you, but I’m writing for my own benefit anyway. I mentioned the ‘out method parameter’ yesterday because I saw it used in a custom library I’m using and then today I found out that the Double class uses it as well. I think it’s a great example of how it should be used. It’s used in the TryParse method:

public static bool TryParse(
   string s,
   NumberStyles style,
   IFormatProvider provider,
   out double result
);

The TryParse method is like the Parse method, except this method does not throw an exception if the conversion fails. If the conversion succeeds, the return value is true and the result parameter is set to the outcome of the conversion. If the conversion fails, the return value is false and the result parameter is set to zero.

I like it because throwing an exception (ie: what the Parse() method does) violates rule #39 of Effective Java Programming which says to “… Use exceptions only for exceptional conditions.” Using an out parameter feels cleaner and simpler. Anyone else think so?

One thought on “More on the out method parameter”

  1. This smells bad to me personally, since it makes it too easy for someone to ignore the bool being returned and just use the double as if nothing is wrong. If you want to avoid exceptions, you might at least want to make the “isSucceeded” bool another out parameter instead of the return value; at least then, the programmer has no excuse for ignoring it. Maybe make the double the return value.

    I agree with Rule #39 if it’s talking about not using exceptions to communicate return values. But I suspect perhaps the rationale might be for performance reasons, since historically in Java it was extremely expensive to throw exceptions. (Is this still the case?)

    If the latter is the main reason, then not throwing the exception IMO can be considered just a performance optimization, not a cleaner and simpler API.

    I think the main thing that makes “out” useful in C# is when you need to have multiple return values and don’t feel like whipping up a new struct or class. Too bad you can’t have multiple return values, like you can do in Ruby or Python. Also, a lot of COM and Win32 interfaces use out parameters, so they’re needed in C# for nice interop.

Leave a Reply

Your email address will not be published. Required fields are marked *