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
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 (writing var
and writing the type) have exactly the same behaviour. So it's not a critical rule. I wouldn't forbid var
, I would just use "Prefer..."
Eric Lippert sums it up well:
My own opinion: I find it harder to read and a bit pointless with types such as int
, string
, bool
or even a User
. It's about readability after all (except where using it with LINQ), so when vars are splattered about it can be harder to read and defeating the purpose of the keyword that the language designers intended it for.
In most cases when uses sensibly (i.e. a simple type initializer where the type and value are the same), then it is fine.
There are some times when it is unclear that you've broken things by changing it - mainly, when the initialized type and the (original) variable type are not the same, because:
In these cases, you can get into trouble with any type resolution - for example:
In such cases, you change the meaning of the code, and execute something different. This is then a bad thing.
Examples:
Implicit conversion:
static void Main() {
long x = 17;
Foo(x);
var y = 17;
Foo(y); // boom
}
static void Foo(long value)
{ Console.WriteLine(value); }
static void Foo(int value) {
throw new NotImplementedException(); }
Method hiding:
static void Main() {
Foo x = new Bar();
x.Go();
var y = new Bar();
y.Go(); // boom
}
class Foo {
public void Go() { Console.WriteLine("Hi"); }
}
class Bar : Foo {
public new void Go() { throw new NotImplementedException(); }
}
etc
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.
var
is the latest "how to lay out your braces"/hungarian notation/Camel casing debate. There is no right answer, but there are people who sit at the extremes.
Your friend is just unfortunate they work below one of the extremists.