When It’s Okay To Use C# 3.0 var
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
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
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.
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.