Using Var Pattern in C # 7

I saw this example var template in new C # 7

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

What is the difference between using:

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

And when this template is a useful solution.

+11
source share
3 answers

There is no practical difference in this example. Unfortunately, so many sites use this - even a language reference .

The main reason you would use the x is var y pattern is the x is var y variable if you need a temporary variable inside a boolean expression. For instance:

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

By creating the temporary variable count we can use it several times without sacrificing performance when calling Count() every time.

In this example, we could use is int count instead - var is just a stylistic choice. However, there are two cases where var is required: for anonymous types or if you want to allow null values. The latter because null does not match any type.

In particular, for if , however, you can do the same: if (list.Count() is var count && count >= min && count <= max) . But this is clearly stupid. The general consensus seems to be that it makes no sense to use it in if . But language does not bother you, because the prohibition of this particular form of expression in this particular expression of expression will complicate the language.

+20
source

Since the question asked here by InBetween explains one use of the var pattern, this is when switch statements are used 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; } 

A.S. Aydin said Adn in his answer.

+1
source

Syntax

 if (o is SomeType x) 

Is a shorthand for

 SomeType x; if (o is SomeType) { x = (SomeType)o; 

This allows you to save a couple of lines that do not really make a significant difference in the code (i.e. declaration and casting).

Also note that it is difficult for you to use var here because you need to provide a type for comparison and discard. Using var will simply return you the same type that x was declared, because the whole compiler will be able to infer.

-2
source

Source: https://habr.com/ru/post/1271235/


All Articles