Why matching patterns to zero result in syntax errors?

I like to use pattern-matchingin nullable intt nullable int int?.:

int t  = 42;
object tobj = t;    
if (tobj is int? i)
{
    System.Console.WriteLine($"It is a nullable int of value {i}");
}

However, this leads to the following syntax errors:

"i)" is marked with a red wavy line.

The expression compiles when using the old statement is:

int t = 42;
object tobj = t;    
if (tobj is int?)
{
    System.Console.WriteLine($"It is a nullable int");
}


string t = "fourty two";
object tobj = t;
if (tobj is string s)
{
    System.Console.WriteLine($@"It is a string of value ""{s}"".");
}

Also works as expected.

(I use and tested both and )

I thought this was due to operator priority. So I tried using brackets in several places, but that didn't help.

?

+11
2

: x is T y, case T y .., , x null. , null , " null ?" .

t is int? i t is int? i t is Nullable<int> i : t int, t int t is int i , null, .

, t is int? i t is int? i or t is Nullable<int> i , , .

, t is int? i t is int? i - , , , t is int? "it an int": "no int here" t is int? "it an int": "no int here" , - ? .

, , (, , ) : . , .

+14

:

int t = 42;
object tobj = t;
if (tobj is Nullable<int> i)
{
    Console.WriteLine($"It is a nullable int of value {i}");
}

:

  • CS8116: "int?" ? ; 'int' ( CS8116 )

( @Blue0500 github) Roslyn β„– 20156. Roslyn # 20156, Julien Couvreur Microsoft , , .
Neal Gafter Microsoft, Roslyn,

tobj is int? i, , tobj is int? i tobj is Nullable<int> i.

+2

Source: https://habr.com/ru/post/1692421/


All Articles