I've just started using ReSharper with Visual Studio (after the many recommendations on SO). To try it out I opened up a recent ASP.NET MVC project. One of the first and most frequent things I've noticed it suggesting is to change most/all my explicit declarations to var
instead. For example:
//From This:
MyObject foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
//To This:
var foo = DB.MyObjects.SingleOrDefault(w => w.Id == 1);
and so on, even with simple types such as int
, bool
, etc.
Why is this being recommended? I don't come from a computer science or .NET background, having "fallen into" .NET development recently, so I'd really like to understand what's going on and whether it's of benefit or not.
It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types. The complaint that var reduces readability is not shared by everyone.
var requires less typing. It also is shorter and easier to read, for instance, than Dictionary<int,IList> . var requires less code changes if the return type of a method call changes. You only have to change the method declaration, not every place it's used.
Refactoring to replace var with an explicit type Use this refactoring to replace var in a local variable declaration with an explicit type. This refactoring applies to: C#
var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.
What ReSharper suggests is clearly overuse of the var keyword. You can use it where the type is obvious:
var obj = new SomeObject();
If the type is not obvious, you should rather write it out:
SomeObject obj = DB.SomeClass.GetObject(42);
One reason is improved readability. Which is better?
Dictionary<int, MyLongNamedObject> dictionary = new Dictionary<int, MyLongNamedObject>();
or
var dictionary = new Dictionary<int, MyLongNamedObject>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With