csharplang
csharplang copied to clipboard
Champion: Type Patterns (VS 16.8, .NET 5)
I propose to permit a type as a pattern:
pattern
: type-pattern
| // all of the existing forms
;
type_pattern
: type
;
This retcons the existing is-type-expression to be an is-pattern-expression in which the pattern is a type-pattern, though we would not change the syntax tree produced by the compiler.
One subtle implementation issue is that this grammar is ambiguous. A string such as a.b can be parsed either as a qualified name (in a type context) or a dotted expression (in an expression context). The compiler is already capable of treating a qualified name the same as a dotted expression in order to handle something like e is Color.Red. The compiler's semantic analysis would be further extended to be capable of binding a (syntactic) constant pattern (e.g. a dotted expression) as a type in order to treat it as a bound type pattern in order to support this construct.
After this change, you would be able to write
void M(object o1, object o2)
{
var t = (o1, o2);
if (t is (int, string)) {} // test if o1 is an int and o2 is a string
switch (o1) {
case int: break; // test if o1 is an int
case System.String: break; // test if o1 is a string
}
}