Should I var or not!

November 7th, 2008  | Tags: ,

A lot of people that I have spoken to about using var in declarations didn’t really get it at first they mistakenly thought that it was either the same as using object or that it was the same as variant in VB 6. This is not the case var does produce strongly typed code just as if you had specified the type yourself.  The next problem that people tend to have with var is that it makes your code harder to read, I think that using var is like a lot of things in programming if you use it responsibly then there is no problem.  So I guess that the real question should be where and when should I use it, here are my thoughts.

Basically you should use var when it is clear exactly what type will be used, if there can be any chance of ambiguity then don’t you it you code will not be clear to anyone that is looking at it.  Another good place to use var is with linq expressions the compiler will auto-magically assign the right type at first this might not be obvious but because IQueryable<T> derives from IEnumerable<T> if you specify that the type is IEnumerable<T> then you will lose the benefit of the IQueryable<T> interface this is particularly apparent when the expression runs against the database you have limited how much of the execution can be off loaded to the database which might mean that you return more data than is necessary.  Any benefit that you might have seen from carefully creating indexes on the database tables will be nullified and the grunt work will have to be done my the IEnumerable<T> code.

No comments yet.
TOP