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

About Rob Sanders

IT Professional and TOGAF 9 certified architect with nearly two decades of industry experience, 18 years in commercial software development and 11 years in IT consulting. Check out the "About Rob" page for more information.

Leave a comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>