[Proposal] Default method return value #9188
Unanswered
MV10
asked this question in
Language Ideas
Replies: 2 comments 1 reply
-
IMO, the existing syntax is much clearer and easier to read, despite being more verbose. As for what a method might return in different circumstances, that is what documentation comments are for. Even if there was a concept of a "default" return value, you'd still need some kind of description as to when it actually would apply. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Sometimes I do this for returning default value: bool Method()
{
if (!Check1()) goto ReturnFailed;
if (!Check2()) goto ReturnFailed;
// Method body
return true;
ReturnFailed:
return false;
} I think it is clear enough. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Quite regularly, I write methods that exit early with some default value (most commonly
null
ortrue
orfalse
). It would be handy if the method return value supported syntactic sugar to specify a default, such that the code could simply invokereturn;
to exit. Such a method signature also provides useful information to the caller.A trivial example declaring that
false
is the default return value:I recognize this could become somewhat messy-looking for returning complex types, but in my experience those aren't common default return values. While it isn't my preference, I also considered syntax within the method itself:
That syntax would also make it more "sensible" to do things like make an input argument the default return value, although I think I still prefer that the default is part of the signature. I suppose it could also be confusing versus the current meaning of the
default
keyword, such asreturn default;
so I pondered a third approach (which is somewhat reminiscent of property default values):However, this wouldn't work with expression-bodied methods, as far as I can see.
For return types involving generics, I'm not sure supporting default return values makes sense (or perhaps there could be a rule that only
null
is permitted), but again, I haven't really seen many cases where a complex type is a default return value (andreturn default(T)
does work, so maybe my concern is misplaced).This probably fails the LDT's "effort / value" tradeoff, but it has occurred to me many times over the years (often when I can't remember what some call's default is, so as the consumer I wish it was explicit and reported by Intellisense), so I figured I'd throw it out there.
Beta Was this translation helpful? Give feedback.
All reactions