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#?
The writers of the .Net Framework Design Guidelines (awesome book) that came out in November 2008 recommend considering using
varwhen the Type is obvious and unambiguous.On the other hand, if using
varwould 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:
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
varand 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
varfor simple types actually helps readability and we must not forget that there is also no performance penalty for usingvar.