CSharp 3.0 introduced the var keyword for declaring variables without having to explicitly specify the type. This was done for using anonymous types returned from LINQ queries. Now, I am seeing many developers use it all over their code and think its a good thing.
Wasn’t C# developed to enforce strongly typed programming?
Var just makes it harder to infer the type when reading and maintaining code.
Take for example this LINQ Query:
var user = from u in Users where user.Status == UserStatus.ActiveIt is hard enough to infer the type from the above query, let alone infer the type from a statement like this:
var index = 1; (Is index an int, long?)Just because a compiler can infer the type does not mean a human should have to be forced to do it when reading it. If we wrote code just to make compilers happy we should be writing Assembly. Why then use an Object Oriented Language? But since code is written for developers to be able to read and maintain it and not just for compilers to compile it, it should be as descriptive and readable as possible.
Some say it cuts down on repetitive code when used in a statement like this:
var user = new User();
For those who are so obsessed with cutting down characters and lines of code, here is a small piece of advice that will better save you coding time and characters: focus on better design and architecture. If you are so concerned about repetitive code – your energy will be well rewarded. Well designed code is always shorter, cleaner, easier to read and also works better!
Cutting down on type names is like removing the wrapper from a drink. You have to infer what is in it by drinking it. For those who don’t care about their calories go ahead, but for the rest us, please put the wrappers!The only time you really have to use var is for anonymous types. There is no other way to get an anonymous type. For everything else a type name can and should be used for variable declaration.
So for those var abusers, spare the rest of us some inferring and just declare your variables with a type name.