Consider the following, at first glance absurd, pattern match:
string s = null;
if (s is string ss) //false
if (s is string) //false
Both is
will return false
. However if we use var
the behavior changes completely:
string s = null;
if (s is var ss) //true!?!
If you hover over var
in VS2017, the type is string
but the behavior of is
is completely different. The compiler is doing something radically different even though the inferred type is the same. How can this be? Is this a bug? Is the null
type somehow bubbling out?
C# pattern matching provides more concise syntax for testing expressions and taking action when an expression matches. The " is expression" supports pattern matching to test an expression and conditionally declare a new variable to the result of that expression.
C# pattern matching is a feature that allows us to perform matching on data or any object. We can perform pattern matching using the is expression and switch statement.
The is pattern expression is a piece of code that evaluates to bool , and it can contain patterns that are combined with and and or . Look at the snippet below where you can see both in action. Note how && is used to combine bool values and how and is used to combine the two relational patterns >= 1980 and <= 1989 .
The C# language reference confirms the behaviour is intended.
A pattern match with the var pattern always succeeds. Its syntax is
expr is var varname
Where the value of expr is always assigned to a local variable named varname. varname is a static variable of the same type as expr.
Note that if expr is null, the is expression still is true and assigns null to varname.
Source: MSDN - C# Language Reference
var
patternThe var pattern just copies the source variable into a new named variable which you can then build a case block expression with like below
string s = null;
var collection = new string[] { "abb", "abd", "abc", null};
switch (s)
{
case "xyz":
Console.WriteLine("Is xyz");
break;
case var ss when (collection).Contains(s):
Console.WriteLine("Is in list");
break;
default:
Console.WriteLine("Failed!");
break;
}
Output:
> Is in list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With