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.
b22eb584-f3d4-49d8-a5b5-865fd54b0438|0|.0