2008-06-14

var in C#

So this looks like yet another flame-provoking topic. Use var or not? Many say this is matter of taste, and that this is analogous to weak typing vs strong typing - both exist successfully.

var i = short.MaxValue;
i++;

Oh well, nobody uses other integer types beside int today anyway. Similar to var, eh? "I don't care what are limits for this type, all that i am interested is that it contains integers". In case of int, i agree, this is most often the best choice, it eliminates the need of typecasting on arithmetic oparations with different types, and few (k)bytes spared are probably not worth headaches choosing between "short" and "int". The similarity is that both reduce the need of thinking.
Matters with var are a bit different. In fact, it does not change semantics of the program, it just makes it a little bit less verbose, ie eliminate some "syntactic noise". So for me this is all about how much redundancy do we need in our code? If there is too much, the code is bloated and it is difficult to find what you need. If, on the other hand, there is too little, it can be hard to understand intent of the code. Talking about verbosity, i always remember code contracts. For me, code contracts look like very nice idea, and although i have never used them, i feel they will appeal to me much more than unit tests, when i have a chance to use them.
Personally, i never use var when not necessary(with anonymous types). Who says it saves typing? Gee, are you programming in notepad or what? In VS IDE, you write first three letters of type name and hit space, 80% you have the right type... Only thing i can imagine you save here is code size, and that's why i will probably use var in my homemade 100-loc programs. For some reason i just feel offended when i see peer programmers writing something like

var client = order.Client;

But again, i feel this is just something you have to get used to. I feel i may change with time, and will be eagerly using this feature everywhere i can, until i start abusing it, which will cause other problems, until i settle on a golden middle, or well, be forced there by some coding standard rules. On a side note, similar feature is proposed for C++0x (auto), a language i have deep trust in.

No comments: