Code Heaven

Jul 07

I don't get var

I've been reading a lot about C# 3.0. I have to admit that I'm late to the game here -- I'm still using 2.0 (and CLR 2.0) for the very vast majority of my projects. I'm not up to speed on functional programming, lambda expressions, and all the other new features yet.

But there's one feature that's been making a lot of noise lately, and that's C#'s new var keyword. See yTechie: Using "var" to simplify code and avoid redundancy, or CodingHorror: Department of Redundancy Department. var is used to lazy-define a variable:

var foo = new StringBuilder();

can be used instead of:

StringBuilder foo = new StringBuilder();

OK. So what?

Yes, var is less redundant than the second variation. As IanG noted in 2005, Var Isn't Object, and more recently, Richard Dingwall exposed the differences between it and genuine variants -- it provides full strong-typing, and the tooling supports complete Intellisense. From the compiler's standpoint, both lines of code above are equivalent.

Richard's post is, in my mind, spot-on. He points out that var exists to support so-called anonymous types -- data types you create inline. (See his post for a bit more on that.) In this scenario, it's the ideal keyword with the ideal usage.

I don't claim to "get" anonymous types yet, either, to be honest. I'm sure they have their uses, but I've not identified any in my projects just yet. But until then, I'll stick with my "redundant" declarations -- even in C# 3.0. I think the code's more readable that way.

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# July 7, 2008 3:34 PM