I have often this kind of code:
public bool MyRoutine(TheModel model)
{
if (string.IsNullOrWhiteSpace(model.Owner))
return false;
...
This way I always need to check the result of the validation routine and place the return inside the if, or something similar.
To keep the code cleaner and to better detect the validation code I would like to write something like this
public bool MyRoutine(TheModel model)
{
Check.ReturnFalseIf (string.IsNullOrWhiteSpace(model.Owner))
...
I would like to write something similar to the Assert.IsTrue(...)
, but instead of have a critical error I would like to return.
Is it possible to do this in c#?
No, there's nothing like this. It would be fine if you were trying to throw an exception - and indeed I have a bunch of Precondition.CheckXyz
methods that do exactly that sort of thing - but there's no "conditional return statement" which is what you're looking for, effectively.
See more on this question at Stackoverflow