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

后端 未结 4 801
情深已故
情深已故 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

    Without checking the design notes on Github I'd guess this was added more for consistency with switch and as a stepping stone for more advanced pattern matching cases,

    From the original What’s New in C# 7.0 post :

    Var patterns of the form var x (where x is an identifier), which always match, and simply put the value of the input into a fresh variable x with the same type as the input.

    And the recent dissection post by Sergey Teplyakov :

    if you know what exactly is going on you may find this pattern useful. It can be used for introducing a temporary variable inside the expression: This pattern essentially creates a temporary variable using the actual type of the object.

    public void VarPattern(IEnumerable s)
    {
        if (s.FirstOrDefault(o => o != null) is var v
            && int.TryParse(v, out var n))
        {
            Console.WriteLine(n);
        }
    }
    

    The warning righ before that snippet is also significant:

    It is not clear why the behavior is different in the Release mode only. But I think all the issues falls into the same bucket: the initial implementation of the feature is suboptimal. But based on this comment by Neal Gafter, this is going to change: "The pattern-matching lowering code is being rewritten from scratch (to support recursive patterns, too). I expect most of the improvements you seek here will come for "free" in the new code. But it will be some time before that rewrite is ready for prime time.".

    According to Christian Nagel :

    The advantage is that the variable declared with the var keyword is of the real type of the object,

提交回复
热议问题