I find myself doing this a lot.
if( obj == null || !obj.SomeMethodThatReturnsABoolean() ) {
// then do this
}
I mean, I just see it cluttering up code in a lot of places. It isn’t really a bad thing, but what’s the fun of syntactical sugar if you can’t sprinkle it around here and there where it makes things slimmer?
So I tried to just make a very humble little method, IsNullOrFalse. The idea is that it will test for what was passed in, see if it is null, and if not, it will run the method, and return the boolean result.
This has actually proven a lot harder than I imagined. I don’t really need this to continue on in any project, but at this point I have gone from curious to intrigued.
Has anyone else done something like this? The problem I am getting is that I cannot pass in something that does not exist that contains a method.
A slightly more generic version of @JaredPar’s answer:
And usage:
This can return return any type, not just bool, so for instance you can do something like: