Thursday, December 5, 2013

Var-ious Thoughts

I started my programming career as a Smalltalker (before Java or C# even existed) and enjoyed the "everything is an object" dynamically-typed variables. In the late 90's, I worked on the VisualAge for Java product (which eventually became the Eclipse platform) using Java. Then I switched jobs and ended up using VB6. It wasn't as bad as I feared because VB6 at least had objects, classes and interfaces (but no inheritance). Still, I was happy when I convinced my bosses that we should switch to C#. It was nice to be back using a fully object-oriented language.

Coming from a Smalltalk background I had been reluctant to embrace a strongly-typed language (let alone strongly-type collections). I found after awhile I liked the some of the benefits like having the compiler catch type exceptions and having the type declaration be a way of self-documenting the code. With the introduction of the var keyword in C# 3.0 I was concerned that we were taking a step back to the VB days. I understood the scenarios with anonymous types they needed to add it for but didn't want to lose documentation benefits. I've come to realize that when you are declaring a variable and then instantiating and assigning an object to it 'var' can save a bunch of typing. Just don't overuse it when the type declaration is not readily apparent (ie don't make me think or have to search to figure out the type).

Here are my general guidelines for using 'var':

  1. Don't use 'var' when the type of variable is not readily apparent.
  2.   var s = SomeMethod();
  3. Use 'var' when declaring a variable and assigning an obvious type to it.
  4.    var collection = new List<string>();
  5. Use 'var' when required to (e.g. with anonymous types).
  6.   var anon = new { Name = "Joe", Age = 34 };

1 comment:

Brad Patton said...

After writing this found someone else that shares the same thoughts. See The C# Keyword var is Evil