Wednesday 11 September 2013

Best Practices for using var in C#

Var was introduced in version 3 of C# and Resharper was updated such that now, any time you don't use a var, Resharper shouts at you and highlights the offending line by underlining it in a squiggly green line.




However, sometimes C# developers can get a little bit 'var happy' and turn everything into a var, which isn't always a good idea.  The most 'non-functional requirement', if you will, that a developer should fulfil is to produce code that is readable and easy for another person to understand quickly.  The extra minute or two it takes to understand a simple line of code may seem like nothing, but if this extra time is required to understand a whole chunk of code the time adds up.

Here are a few examples of when and when not to use var.

Example 1


Consider the following code:

Dictionary<string, List<Person>> myDictionary = new Dictionary<string, List<Person>();

Talk about LONG WINDED.  This is clearly a good candidate for var.

                      var myDictionary = new Dictionary<stringList<Person>();

I think we all agree that it it obvious what time the variable 'myDictionary' is.

Example 2

var hobby = person.Hobbies.First("baseball");

This is slightly more ambiguous that the previous example.  What are we returning? Is is perhaps an object of type 'Hobby' or maybe 'IHobby' or what about 'Baseball'?  It is obvious that we are returning something to do with someone's hobby but without knowing the codebase or going and looking inside the Person class we don't know what object we are dealing with.

If there are a string of method calls then avoid assigning the result to a var.

Example 3

var i = 1;
var s = "hiya";

Apart from the fact that I think that 1-character variable names are of the devil (except inside a loop) this is fine. It is obvious that these are an int and string respectively.

Summary

In general, follow your instincts.  I think it is far worse to write ambiguous code overusing var that to be a bit long winded and spell everything out.

It is also worth mentioning that if you are using var, it is generally a good idea to make sure that your variables are named appropriately (though of course you should be doing this anyway regardless of whether or not you are using var :) ). 

No comments:

Post a Comment

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning&#...