I am tired of writing:
if(objectA!=null)
return;
or:
if(objectB==null)
return;
So I was hope to shorten this snippet, to something like this:
Returns.IfNull(objectA);
it is pretty match the same length but usually there are few objects to check and adding params as parameter can shorten:
if(objectA==null || objectB!=null || objectC!=null)
return;
to:
Returns.IfNull(objectA,objectB,objectC);
Basically function IfNull have to get access to function one step higher in stack trace and finish it. But that’s only idea, I don’t know if it’s even possible. Can I find simililar logic in some lib?
No, you are essentially asking the function to exit the function higher than itself which isn’t desirable nor really possible unless you throw an exception (which isn’t returning per se).
So, you can either do your simple and concise if-null-return checks, or what you may want to do there instead is to throw a well defined exception, but I don’t recommend exceptions for flow-control. If these are exceptional (error) circumstances, though, then consider throwing an ArgumentNullException() and handling it as appropriate.
You could write some helper methods to throw ArgumentNullException() for you, of course, to clean it up a bit:
Then you could write:
But once again, this is exceptions and not a “return” of the previous method in the stack, which isn’t directly possible.