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.
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);