The Daily WTF
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
To read the full article click on the 'post' link at the top.