Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behavior in pattern matching when using var or explicit type

Tags:

c#

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?

like image 429
InBetween Avatar asked Aug 27 '17 10:08

InBetween


People also ask

How to do pattern matching in c#?

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.

Which allows us to perform matching on data or any object in C#?

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.

Is Pattern A expression?

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 .


1 Answers

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


The var pattern

The 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
like image 156
Aydin Avatar answered Sep 22 '22 14:09

Aydin