I am working on a .NET project where the team decided to sidestep the convention of Exceptions in favor of a custom error signal. In practice, the concept works well enough, except there is one nasty side effect: I find myself constantly checking intermediate error codes before deciding whether to proceed:
var error = DoSomething();
if( !error.Success )
return error;
return DoSomethingElse();
What I would like to do is something like the following:
DoSomething().ReturnIfError();
return DoSomethingElse();
I know some languages such as Ruby support the ‘return if’ construct – is there any such thing in C#, or would it be possible to do so in an extension method?
This is not something that can be prettily hacked in with extension methods.
In the second example you gave (with the theoretical method chaining), you would…
DoSomethingDoSomethingerrored out, callReturnIfErrorDoSomethingElseYou need to use the
returnkeyword to break out of a method block early.Assuming that this is what you really want to do, then the following code can make that happen (not that I recommend it!).