Search code examples
c#coding-styleimplicit-typing

Why would var be a bad thing?


I've been chatting with my colleagues the other day and heard that their coding standard explicitly forbids them to use the var keyword in C#. They had no idea why it was so and I've always found implicit declaration to be incredibly useful when coding. I've never had any problems finding out what type the variable was (you only hover over the variable in VS and you'll get the type that way).

Does anyone know why it would be a bad idea to use the var keyword in C#?


Solution

  • The writers of the .Net Framework Design Guidelines (awesome book) that came out in November 2008 recommend considering using var when the Type is obvious and unambiguous.

    On the other hand, if using var would result in an ambiguity when reading the code, as Anton Gogolev pointed out, then it's better not to use it.

    in the book (Annex A), they actually give this example:

    var names = new List<string>(); // good usage of var
    
    string source = GetSource();
    var tokens = source.Split(' '); // ok; most developers know String.Split
    
    var id = GetId(); // Probably not good; it's not clear what the type of id is
    

    It's possible that, to ensure that readability is not subjected to the whims of lowly developers, your organisation has decided that you were not worthy of var and banned it.
    It's a shame though, it's like having a nice tool at your disposal but keeping it in a locked glass cabinet.

    In most cases, using var for simple types actually helps readability and we must not forget that there is also no performance penalty for using var.