When It’s Okay To Use C# 3.0 var

Tom 373 words

I ragged a little bit on “var” a while ago, but there are some cases where I think it’s a handy shortcut.  Those being when it’s abundantly clear what the underlying type is, like when creating new objects.  For example, it makes perfect sense to change this:

CustomerDataContext db = new CustomerDataContext();

To this:

var db1 = new CustomerDataContext();

It’s clear to me at a glance what’s going on when I’m reading it, and there’s no needless redundancy.

(By the way, you can’t use “var” in a class-level declaration, only in local declarations.  I don’t know why, either… it feels like a completely arbitrary restriction.)

The problem area for “var” is when you use it with method calls, ie. changing something like this:

FileInfo[] dirs = GetFiles();

To this:

var dirs1 = GetFiles();

You suspect it’s returning a collection of files by looking at the method name, but you don’t know for sure and you don’t know exactly what kind of collection.  It could be an Array or a List or an ArrayList or an IEnumerable or an IEnumerable.  In that situation, I would probably discourage people — especially less experienced people* who tend not to write descriptive variable and method names - from using a var shortcut.  (You can always hover the mouse over GetFiles to see the method signature and return type, but that’s an extra step.)

I also wonder about using var as the return type for LINQ queries.  Sure, we all know from experience that you’re getting back an IEnumerable collection of one type or another, but what about someone who’s just out of college*, looking at a LINQ query for the first time?  That person probably won’t understand the LINQ query syntax or “var” (since I doubt it is taught in any school), but I would think they’d know what to do with an IEnumerable.

Maybe I’m being a little too alarmist there.  I guess using LINQ queries at all should imply a certain level of knowledge to work with the source code.

  • The older I get, the more I find that a lot of my code crafting efforts go toward making the codebase ready for less experienced programmers to work with.  Which basically means:  Simplify, simplify, simplify.

Originally posted on my personal blog which was active from 2003 to 2020. You may have arrived here by redirection from the original permalink.

Elsewhere: Loading...

Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.