Sunday, December 19, 2010

Using Var + As, a Neat Little Trick

Perhaps this is something everyone already knew about, but I recently came across this little C# combo that solves one of my major outstanding issues with the var keyword.
I consider var to actually be quite a useful language feature to reduce repetition and make your code slightly more flexible for refactoring, but I’ve always had one little problem with it.

What if I want a base class type or interface?
I most often run into this problem when I am working with lists.
Have you ever written some code like this?

var myList = new List<int>();

The problem with this code is that we are stuck with the concrete List implementation for our variable myList, because we don’t have a way of specifying that we actually want an IEnumerable to be our reference type.

The solution is so simple that I am a bit surprised I didn’t think of it earlier.
I had always assumed that I just couldn’t use var there and would have to declare the type like so:

IEnumerable<int> myList = new List<int>();

But we can actually just use as to keep our var in place if we want to.

var myList = new List<int> as IEnumerable<int>

Read more: Making the Complex Simple