Weird behavior on zero- or one- element tuple deconstruction pattern matching #6218
-
Hello. I just tested the cases on zero- and one- element tuple deconstruction pattern matching: object o = new C();
var p = new C();
// Zero-element tuple deconstruction pattern checking
if (o is C ()) Console.WriteLine(); // OK. Treat as 'is C' pattern
if (o is ()) Console.WriteLine(); // OK. Treat as 'is ITuple { Length: 0 }' pattern
if (p is C ()) Console.WriteLine(); // OK. Treat as 'is not null' pattern
if (p is ()) Console.WriteLine(); // OK. Treat as 'is not null' pattern
// One-element tuple deconstruction pattern checking
if (o is C (42)) Console.WriteLine(); // OK. Calls 'Deconstruct(out int)'
if (o is (42)) Console.WriteLine(); // OK but treat as 'is 42' instead of 'is (innerValue: 42)'
if (p is C (42)) Console.WriteLine(); // OK. Calls 'Deconstruct(out int)'
//if (p is (42)) Console.WriteLine(); // Wrong. 'p' is not an integer
if (p is (innerValue: 42)) Console.WriteLine(); // OK.
class C
{
public void Deconstruct() { }
public void Deconstruct(out int innerValue) => innerValue = 42;
} I wonder why the pattern Thank you. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Wrapping an expression in parenthesis doesn't change it's type or value. That's always been true in C#. That does create an ambiguity with recursive positional patterns, which were added after constant patterns, and that's why you must explicitly disambiguate. You can also include the type pattern: if (p is P(42)) Console.WriteLine(); // OK |
Beta Was this translation helpful? Give feedback.
Wrapping an expression in parenthesis doesn't change it's type or value. That's always been true in C#. That does create an ambiguity with recursive positional patterns, which were added after constant patterns, and that's why you must explicitly disambiguate. You can also include the type pattern: