Annoying nullable behavior in C#
Take a look at this line of code:
if (cmd.Def?.ColumnDef is not { } column) {
return;
}
// do something with column Do you understand it? Would you write something like that?
This is using the relatively new pattern matching behavior in C# and basically says "if ColumnDef is not a not null object that would otherwise be stored in a column variable, return". If your brain hurt at the "not a not null" part, you are not alone.
Normally I would have written this differently:
var column = cmd.Def?.ColumnDef;
if (column is null) {
return;
}
// do something with column There is a difference, though? Can you see it? Read the title of the post. Do you see it now?
The difference is in the type of the column variable in the two cases. The first matches anything that is not null to column, so column will be non-nullable there. In the second block, column will have the nullable version of whatever type ColumnDef was. So if ColumnDef is a string (reference type) column is string in the first case and string? in the second case. Damn you nullable aware C# ! If ColumnDef is an int, for example, column will be int in the first case and int? in the second.
The compiler may be smart enough to not warn about column being nullable after the is null check, but the type is already set in stone by then.
The result is that an AI will prefer the first syntax, as it is more correct and also shorter. Some devs might do that too (heck, there are people that *like* to code in Python). But what about reading that code? Ugh!
Comments
Be the first to post a comment