OdeToCode IC Logo

Once More In Defense Of The var Keyword

Tuesday, February 8, 2011

Even today there are those of you who doubt the power of the var keyword in C#! Or rather, there are those of you who steadfastly refuse to use it.

I think the var keyword provides a nice symmetry for local variable declarations. No one variable appears more important than another just because it has a type name with more capital letters.

var newPatient = new Patient();
var surgicalProcedure = Procedures.Rhinoplasty;
var lengthOfStay = TimeSpan.FromDays(2);

We can also talk about readability, type inference - blah blah blah. But, I think the following generalization is the real benefit of the var keyword.

Developers who use the var keyword tend to take greater care in naming their variables.

I think the carefulness is a natural reaction to the lack of type information.  I've seen quite a bit of code like this:

Procedure proc = Procedures.Rhinoplasty;

But, rarely do I see abbreviations and shortcuts with var.

var surgicalProcedure = Procedures.Rhinoplasty;

If you are still wary of var, give it a try for the day. I think your variable names will thank you.