Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the standard behaviour for an out parameter when a TryXxxx method returns false?

Assuming a method with the following signature

bool TryXxxx(object something, out int toReturn)

What is it acceptable for toReturn to be if TryXxxx returns false?

In that it's infered that toReturn should never be used if TryXxxx fails does it matter?

If toReturn was a nulable type, then it would make sense to return null. But int isn't nullable and I don't want to have to force it to be.

If toReturn is always a certain value if TryXxxx fails we risk having the position where 2 values could be considered to indicate the same thing. I can see this leading to potential possible confusion if the 'default' value was returned as a valid response (when TryXxxx returns true).

From an implementation point if view it looks like having toReturn be a[ny] value is easiest, but is there anything more important to consider?

like image 459
Matt Lacey Avatar asked Mar 15 '10 11:03

Matt Lacey


2 Answers

I would explicitly document it as using the default value for the type (whatever that type is; so 0 in this case but default(T) in a more general case). There are various cases where the default value is exactly what you want if the value isn't present - and in that case you can just ignore the return value from the method.

Note that this is what methods like int.TryParse and Dictionary.TryGetValue do.

like image 89
Jon Skeet Avatar answered Nov 15 '22 04:11

Jon Skeet


It could be default(int):

bool TryXxxx(object something, out int toReturn)
{
    toReturn = default(int);
    return false;
}
like image 34
Darin Dimitrov Avatar answered Nov 15 '22 04:11

Darin Dimitrov