Submitter “NotAThingThatHappens” stumbled across a “unique” way to check for nulls in C#.
Now, there are already a few perfectly good ways to check for nulls. variable is null
, for example, or use nullable types specifically. But “NotAThingThatHappens” found approach:
if(((object)someObjThatMayBeNull) is var _)
{
//object is null, react somehow
}
else
{
UseTheObjectInAMethod(someObjThatMayBeNull);
}
What I hate most about this is how cleverly it exploits the C# syntax to work.
Normally, the _
is a discard. It’s meant to be used for things like tuple unpacking, or in cases where you have an out
parameter but don’t actually care about the output- foo(out _)
just discards the output data.
But _
is also a perfectly valid identifier. So var _
creates a variable _
, and the type of that variable is inferred from context- in this case, whatever type it’s being compared against in someObjThatMayBeNull
. This variable is scoped to the if
block, so we don’t have to worry about it leaking into our namespace, but since it’s never initialized, it’s going to choose the appropriate default value for its type- and for reference types, that default is null
. By casting explicitly to object
, we guarantee that our type is a reference type, so this makes sure that we don’t get weird behavior on value types, like integers.
So really, this is just an awkward way of saying objectCouldBeNull is null
.
NotAThingThatHappens adds:
The code never made it to production… but I was surprised that the compiler allowed this.
It’s stupid, but it WORKS!
It’s definitely stupid, it definitely works, I’m definitely glad it’s not in your codebase.