Usage of Var Pattern in C# 7

There's no practical difference in that example. It's unfortunate that so many sites use that—even the language reference.

The main reason you would use the x is var y pattern if you need a temporary variable within a Boolean expression. For example:

allLists.Where(list => list.Count() is var count && count >= min && count <= max)

By creating temporary variable count we can use it multiple times without the performance cost of calling Count() each time.

In that example we could have used is int count instead—the var is just a stylistic choice. However, there are two cases where var is needed: for anonymous types or if you want to allow nulls. The latter is because null doesn't match any type.

Specifically for if, though, you could do the same thing: if (list.Count() is var count && count >= min && count <= max). But that's clearly silly. The general consensus seems to be that there's no good use for it in if. But the language won't prevent you, because banning this particular expression form from that specific expression-taking statement would complicate the language.


As the question here asked by InBetween, explains one usage of var pattern is when is use switch statements as follows:

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;

}

AS Aydin Adn said in his answer.