Type Inference

Recently Paul Stovell made reference to this blog post entry by Jared Parsons (no relation to MrAndyPuppy – or M.RandyPuppy as I once misread).
 
The introduction of the implicit type ‘var’ has been somewhat controversial.
 
Some advocate using it by default, and only declaring types where necessary. 
Others disagree that it obfuscates the intention of the code (makes less readable code). 
Yet further, some believe "[var] doesn’t benefit you in any way except that the word ‘var’ may be shorter than your type name" and that "It’s syntactic sugar for the lazy people or for very small scale test projects only"
 
To backtrack.. what we are referring to here is a local variable (within method scope) which infers its type by the definition of the right hand side expression of the assignment.  This is determined by the compiler. 
 
In other words, instead of expressing
MyClass myClass = new MyClass();
you could use
var myClass = new MyClass();
 
Obviously this is a simple example. 
 
The common practice is to use var with LINQ expressions where returning anonymous types, etc.
 
The question is: which camp are you in?  and why?
 
1. Use always
2. Use where practical
3. Avoid unless necessary

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.