Why does pattern matching on a nullable result in syntax errors?
Change your code into:
int t = 42;
object tobj = t;
if (tobj is Nullable<int> i)
{
Console.WriteLine($"It is a nullable int of value {i}");
}
This produces the more helpful:
- CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead (Could not find documentation about CS8116 to reference)
Others (user @Blue0500 at github ) have tagged this behaviour as a bug Roslyn issue #20156. Reacting to Roslyn issue #20156, Julien Couvreur from Microsoft has said he thinks it is by design.
Neal Gafter from Microsoft working on Roslyn has also said better diagnostics are wanted for use of nullable type is switch pattern.
So, the error message can be avoided by using:
int t = 42;
object tobj = t;
if (tobj == null)
{
Console.WriteLine($"It is null");
}
else if (tobj is int i)
{
Console.WriteLine($"It is a int of value {i}");
}
Except for issues when parsing tobj is int? i
, this still leaves the question why is tobj is int? i
or tobj is Nullable<int> i
not allowed.
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.