Why does pattern matching on a nullable result in syntax errors?

The type pattern in its various forms: x is T y, case T y etc, always fails to match when x is null. This is because null doesn’t have a type, so asking “is this null of this type?” is a meaningless question.

Therefore t is int? i or t is Nullable<int> i makes no sense as a pattern: either t is an int, in which case t is int i will match anyway, or it’s null, in which case no type pattern can result in a match.

And that is the reason why t is int? i or t is Nullable<int> i are not, and probably never will be, supported by the compiler.

The reason why you get additional errors from the compiler when using t is int? i is due to the fact that, e.g. t is int? "it's an int" : "no int here" is valid syntax, thus the compiler gets confused over your attempts to use ? for a nullable type in this context.

As to how can you avoid them, the obvious (though probably not very helpful) answer is: don’t use nullable types as the type in type patterns. A more useful answer would require you to explain why you are trying to do this.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)