Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Var Pattern in C# 7

Tags:

I've seen this example of var pattern in the new C# 7

if (o is var x) Console.WriteLine($"it's a var pattern with the type {x?.GetType()?.Name}"); 

What is the different of just use:

var x = o; Console.WriteLine($"it's a var pattern with the type {x?.GetType()?.Name}"); 

And when this pattern is an useful solution.

like image 918
Josbel Luna Avatar asked Aug 23 '17 16:08

Josbel Luna


1 Answers

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.

like image 112
Matt Tsōnto Avatar answered Sep 29 '22 16:09

Matt Tsōnto