I see a lot of C#-questions recently that make use of the
var keyword. For those not familiar with C#/
var (I don't know if other languages have similar features):
You declare something
var and the compiler (and IDE usually already as well) guesses the type you want and watches over that, so the code remains strongly typed.
var potato = functionThatReturnsAString(); //potato is a string now Console.WriteLine(potato); //works var cucumber = 52 * 128; //cucumber is an int now cucumber++; //works var pepper = "green"; pepper++; //won't work as pepper is considererd a string.
The "great innovation" behind that is that you can rapid-fire var-typed variables and can decide upon usage what they shall be / don't need to explicitly change the type in the declaration when you change the type. Just assign an object of the new type instead and it will work.
I don't like it, but that discussion has already been had elsewhere (Stack Overflow).
However, a drawback for Code Review in particular is that it makes it occasionally hard to understand what is going on in the code. Take the first code block from this question:
foreach(var t in blenabled) in connection with the strange naming, this gives us no idea of the type in the List. In that case it is clear from the following code that it is about
bool, but consider numeric types:
You see a line in the code that might cause a division by 0. If the variable in question is an integer type => exception is thrown, if it is
float (etc.) => value NAN is assigned.
From most standard operations you cannot tell at all which numeric type is being used. Or think about
Int64: If you cannot tell the specific type, you cannot safely identify risky casts, overflows etc., even if 99.9% of times it will be
The community should enforce that the
var keyword should only (if at all) be used in questions and answers if the resulting type is obvious.
var pear = myClass.someObj.Value; //NOPE! var apple = myClass.ToString(); //OK.
That means especially when getting values from custom functions or Collections declared outside the code posted, the type should be stated. After all, it is not that hard to just type out the type ONCE per variable.
I do not wish these questions to be closed. I would like the community to be aware of this problem and include into their reviews / comments remarks how and why the usage of
var decreases understandability of code or hinders good reviews.
summary so far