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#?
is indeed a bad thing. However,
is perfectly fine to me.
The bottomline is: use descriptive identifier names and you'll get along just fine.
As a sidenote: I wonder how do they deal with anonymous types when not allowed to use
var
keyword. Or they don't use them altogether?Here are the results of a test I ran on efficiency of
var
versus explicit typing:First Label result is: 00:00:00 000034
Second Label result is: 00:00:00 00008
Surely this is a mistake. It's because some folk don't realise that it is actually strongly typed, and not at all like a var in VB.
Not all corporate coding standards make sense, I once worked for a company who wanted to prefix all class names with the company name. There was a massive rework when the company changed it's name.
It can hurt readability if it is misused. However completely forbidding it is a bit strange as your colleagues will have a tough time using anonymous types without it.
First, as a general rule, coding standards should be discussed and agreed by the team, and the reasoning behind them should be written down, so that anyone can know why they are there. They shouldn't be the Holy Truth from One Master.
Second, this rule is probably justified because code is more times read than written.
var
speeds up the writing, but may slow down the reading a bit. It's obviously not a code behaviour rule like "Always initialize variables" because the two alternatives (writingvar
and writing the type) have exactly the same behaviour. So it's not a critical rule. I wouldn't forbidvar
, I would just use "Prefer..."Forbidding it entirely means forbidding the use of anonymous types (which become incredibly useful as you use LINQ more).
This is stupidity plain and simple unless someone can formalise a good reason to never use anonymous types.