Usage of Var Pattern in C# 7

前端 未结 2 611
情歌与酒
情歌与酒 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:53

    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.

提交回复
热议问题