c# – When do var templates make sense?

Question:

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.

I put in a test method, the thing really works.

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

However, I find it completely pointless. Moreover, the code, as for me, is terribly unreadable and not obvious.

So for what situations is this template actually needed?

Answer:

This can be useful for introducing 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);
    }
}
Scroll to Top