In C # 7.0, var-templates appeared which, judging by the documentation, are always true and are needed to create a new variable with the same type and value.

Threw a test method, the piece really works.

 private void TestPattern(object k) { if (k is var test) Console.WriteLine("Result: " + test.GetType() + " " + test); Console.ReadKey(); } 

However, I find it absolutely meaningless. Moreover, the code is terribly unreadable and not obvious to me.

So for what situations do you actually need this template?

    1 answer 1

    This may be applicable to the introduction of a temporary variable in an expression, for example :

     public void VarPattern(IEnumerable<string> s) { if (s.FirstOrDefault(o => o != null) is var v && int.TryParse(v, out var n)) { Console.WriteLine(n); } } 
    • As a purely indicative example, of course it will, but in general, in essence, this is only a complication of the code with declaring a local variable. At a minimum, the visibility of this variable is not visually obvious, and the condition has become more complicated. Unlike the steep new out var n ! - yolosora
    • @yolosora, what is the fundamental difference between is var and out var? - Grundy
    • Well, out var here cuts the code painlessly. I have always been frosted by the need to declare in advance variables for out-parameters - yolosora
    • one
      This is a replacement for the "operator comma" as it were. - VladD 10:06 pm
    • one
      @VladD, only in the operator the comma could not declare variables :) - Grundy