Usage of Var Pattern in C# 7

前端 未结 2 606
情歌与酒
情歌与酒 2020-12-10 11:30

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}\");
         


        
2条回答
  •  感情败类
    2020-12-10 11:46

    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.

提交回复
热议问题