Why would var be a bad thing?

前端 未结 17 1929
误落风尘
误落风尘 2020-12-04 17:21

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

17条回答
  •  悲哀的现实
    2020-12-04 17:58

    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(); // 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.

提交回复
热议问题