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
var
when the Type is obvious and unambiguous.On the other hand, if using
var
would 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
var
and 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
var
for simple types actually helps readability and we must not forget that there is also no performance penalty for usingvar
.This is really a readability issue with your code.
My personal preference is to only ever use "var" for anonymous types (indeed, if you wish to use anonymous types at all, you'll need to use var), and these mostly come from LINQ queries. In these cases, you have no choice but to use var if your query is projecting into a new (implicit & anonymous) type.
However, C# 3.0 will happily let you use var anywhere you like, outside of LINQ and anonymous types, for example:
is perfectly valid, and myint and mystring will be strongly-typed by the inferred values used to initialize them. (thus, myint is a System.Int32 and mystring is a System.String). Of course, it's fairly obvious when looking at the values used to initialize the variables what types they will be implicitly typed to, however, I think it's even better for code readability if the above were written as:
since you can see immediately at a glance exactly which type those variables are.
Consider this somewhat confusing scenario:
Perfectly valid code (if a little unconventional) but in the above, I know that bbb is a double, despite the initializing value appearing to be an int, but aaa will definitely not be a double, but rather an int.
You may consider Microsoft's opinion to be relevant, since C# is their language:
See MSDN - Implicitly Typed Local Variables (C# Programming Guide), last paragraph.
You should also be aware that var removes the compile-time datatype test on the initial assignment.
Since most variables are only assigned once, consistent use of var removes almost all datatype tests on variable assignments.
This makes your code vulnerable to accidental changes e.g. those made by merge tools or tired developers.
'var' is about being clear
The main debate about whether to use the
var
keyword or not is about how readable the code is to you and other developers.Just as if you were writing a story there is not definitive right answer. But let's look at some examples of this in plain English.
Who went the other way? Jake or Bill? In this case "Jake" and "Bill" are like the type name. And "He" and "him" are like the var keyword. In this case it might help to be more specific. The following for example is much clearer.
In this case being more specific made the sentence clearer. But that's not always going to be case. In some cases being specific makes it harder to read.
In this case it would be easier to read the sentence if we used "he" and in some cases left out his name all together, this is the equivalent of using the
var
keyword.Those analogies cover the gist, but they don't tell the whole story. See in those examples there was only one way to refer to the person. Either with their name, for example Bill, or by a more general way, like "he" and "him". But we're only working with one word.
In the case of the code you have two "words", the type and the variable name.
The question now becomes is there enough information there for you to easily determine what
p
is? Would you still know what people is in this scenario:How about this one:
How about this one:
Or this one:
Or this one:
Whether the keyword
var
works in a given scenario depends a lot on the context of the code, like what the names of the variables, classes, and methods are, as well as the complexity of the code.Personally I like to use the
var
keyword it's more comprehensive to me. But I also tend to name my variables after the type so I'm not really losing any information.That said sometimes I make exceptions, such is the nature of anything complex, and software is nothing if not complicated.
I wrote a blog article on this topic a few months ago. For me, I use it every where possible and specifically design my APIs around type inference. The basic reasons I use type inference are
http://blogs.msdn.com/jaredpar/archive/2008/09/09/when-to-use-type-inference.aspx
Implicit typing is great, and people who flat-out prohibit it damage productivity and invite brittle code.
It's almost like type-safe, compiler-checked duck typing, which is incredibly useful when refactoring. For example, if I have a method which returns a List, and I refactor it to return IEnumerable, then any callers to that method which have used the var keyword and only use IEnumerable methods will be fine. If I've explicitly specified, e.g., List, then I've got to go and change that to IEnumerable everywhere.
Obviously, if any of the implicit-typing callers require List methods, then I'll get compile errors when I build, but if that's the case I probably shouldn't have been changing the return type anyway.