I see this sort of thing in javascript all the time, iffy/falsy statements
if (someUnknownType) {
// will check null | undefined | 0 | false | ''
}
but I've encountered this today in C# for the first time and I can't find seem to find the right words that I can search for this.
_existingInstance = getTheInstanceOrNull();
if (_existingInstance)
DoSomeThings();
I thought it was odd since it didn't explicitly say existingInstance != null
, so I decided to test out a couple things
if (null)
DoSomeThings();
// Err: Cannot convert null to 'bool' because it is non-nullable
I double checked the return type of the method in question, and ended up testing this next
MyType instance = null;
if (instance)
DoSomeThings(); // Roslyn says it's okay
Which I suspected would pass, since it's the source of my doubt. I then proceeded to test one last scenario
bool? doNotPass = null;
if (doNotPass)
DoSomeThings();
// Err: Cannot implicitly convert 'bool?' to 'bool'
What exactly is being checked when a reference type is not explicitly checked against a comparator in a conditional?
I'be been working with C# for a few years now, so if it's well known, is this simply unpopular?
As a last note, I looked at the class definition to make sure there was no operator overload, and I didn't see any