by mathias 5. March 2009 15:54

My first reaction when I learnt that the keyword var had been introduced in C# 3.0 was horror. It comes in part from my past as a VBA developer, which has a similar-looking and named "variant" type. "Variant" is pretty much the equivalent of "object" in C#, which explains my worry: on the surface, a statement like the one below looks like you gave up on all the goodness of type-safety.

var myInstance = new MyClass();

I quickly learnt that var != variant, and that var IS type safe - and after reading the Handbook from the Department of Declaration Redundancy Department, I started using var to instantiate new objects:

EncoderReplacementFallbackBuffer buffer = new EncoderReplacementFallbackBuffer();
var buffer = new EncoderReplacementFallbackBuffer();

... which works great, and makes code more concise, and readable.

But then, with the naive enthusiasm of the new convert, I began to use var left and right, in situations like:

var myValue = MyMethod();

... and got some heat from colleagues, telling me that my code was becoming harder to read. Which makes sense - the statement above works perfectly fine, but you have no way to know what to expect myValue to be unless you check the code for MyMethod(). There are a few positives (faster typing, and somewhat easier refactoring), but compared to the loss in readability, they don't really add up to much. As a consequence, I stopped, and limited the usage to instantiation.

Comments

3/8/2009 7:22:48 AM #

Prema Grandhi

Sorry for being a pain Mathias !! My apologies.

Prema Grandhi United States | Reply

3/9/2009 7:34:11 PM #

Mathias

Nothing to be sorry for - I really got carried away on using var, so thanks for playing the role of Jiminy Cricket, and keeping me on track!

Mathias | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading