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:
public static class ArgumentHelper
{
public static void VerifyNotNull(object theObject)
{
if (theObject == null)
{
throw new ArgumentNullException();
}
}
public static void VerifyNotNull(params object[] theObjects)
{
if (theObjects.Any(o => o == null))
{
throw new ArgumentNullException();
}
}
}
Then you could write:
public void SomeMethod(object obj1, object obj2, object obj3)
{
ArgumentHelper.VerifyNotNull(obj1, obj2, obj3);
// if we get here we are good!
}
But once again, this is exceptions and not a "return" of the previous method in the stack, which isn't directly possible.
You are asking for something that only the language designer can fix for you. I have proposed one thing by myself. The .? operator does return from the current method with the default return value when the argument left to it is null.
return appSettings.?GetElementKey(key).?Value ?? "";
Perhaps we will see it some day in C# 6?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With