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
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