ReSharper, var, and You

After many, many, recommendations I finally got round to trying out ReSharper (aka R#). R# is an awesome plugin for Visual Studio designed to make writing code better, smarter and easier. It also tries to make refactoring as painless as possible by giving hints about where code can and/or should be optimised.

To get started with R# I loaded up an ASP.NET MVC project to see what it would suggest. I knew there was a lot in this particular project which could be done better. To my eternal shame and damnation there was even a section of code that relied on try{} ... catch{} to decide on what action to take (don’t worry, I fixed that – but I’ll probably still go to programmer hell for it).

Anyway, one thing which confused me was R#’s insistence on recommending I change pretty much every explicit type declaration to var instead. So for a block of code like this:

DataBaseDataContext DB = new DataBaseDataContext();
List<MyObject> MyObjectList = DB.MyObjects.Where(foo == bar).ToList<MyObject>();
int ListCount = MyObjectList.Count(); // Yes, this is totally contrived.

Would – if I followed R#’s suggestions to the letter – become:

var Db = new DataBaseDataContext();
var myObjectList = Db.MyObjects.Where(foo == bar).ToList();
var listCount = MyObjectList.Count(); // Yes, this is totally contrived.

This threw me off a bit. Why would it be recommending I change all those type declarations, even the humble int into var? Was this some sort of secret-ninja compiler optimisation? I admit I don’t know C# as well as I’d like yet, having only stumbled into it about 18 months ago, so I asked the question on Stack Overflow.

Very quickly the consensus was R# was suggesting this out purely for readability of code. var Db = new DataBaseDataContext(); is shorter and as easy to understand as DataBaseDataContext Db = new DataBaseDataContext();. Doing this for simple types like int is probably unnecessary, but could be useful later where you want to change the type of a variable (where assigning from a method return, for example). Ultimately though, the suggestion is not for any performance benefit, nor is it a hard-and-fast recommendation. It’s entirely up to you.

So personally I’d implement R# recommendations on the above code like this:

var Db = new DataBaseDataContext();
var myObjectList = Db.MyObjects.Where(foo == bar).ToList();
int listCount = MyObjectList.Count(); // Yes, this is totally contrived.

Add Your Comments

Required
Required
Tips

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <ol> <ul> <li> <strong>

Your email is never published nor shared.

Ready?