What's the benefit of var patterns in C#7?

后端 未结 4 795
情深已故
情深已故 2020-12-25 11:10

I don\'t understand the use case of var patterns in C#7. MSDN:

A pattern match with the var pattern always succeeds. Its syn

4条回答
  •  天涯浪人
    2020-12-25 12:02

    In most cases it is true, the var pattern benefit is not clear, and can even be a bad idea. However as a way of capturing anonymous types in temp variable it works great. Hopefully this example can illustrate this: Note below, adding a null case avoids var to ever be null, and no null check is required.

            var sample = new(int id, string name, int age)[] { 
                                                              (1, "jonas", 50),                                                                                                                            
                                                              (2, "frank", 48) };
    
            var f48 = from s in sample 
                      where s.age == 48 
                      select new { Name = s.name, Age = s.age };
    
            switch(f48.FirstOrDefault())
            {
                case var choosen when choosen.Name == "frank":
                    WriteLine(choosen.Age);
                    break;
                case null:
                    WriteLine("not found");
                    break;
            }
    

提交回复
热议问题