By John Sonmez December 16, 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?

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:

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

So it’s actually a little more verbose, but I think it is a bit more clear, and it is more consistent if you are using var everywhere else.

There has to be a better use

I’ve been racking my brain trying to come up with more useful ways to use this little combo, but I can’t really seem to come up with anything.

It seems like there has to be something else you could use this combo for.

What do you think?  Any ideas?

About the author

John Sonmez

John Sonmez is the founder of Simple Programmer and a life coach for software developers. He is the best selling author of the book "Soft Skills: The Software Developer's Life Manual."