I have a coworker that is against type inference in C#. I believe most of his arguments surrounded lack of readability. My argument against that is that Visual Studio's intellisense features provide a simple way of viewing types, and reading them from the code isn't as necessary as it might be if we were coding out of notepad.
However, I am curious about the advantages and disadvantages of using type inference in C#. I come from C++ and I know that C++0x's 'auto' has a more objective benefit in that you don't always know the types you're getting (especially when doing heavy template programming). An example is using auto to store the value of Boost.Bind.
In C#, type inference doesn't seem to be as much of a requirement so much as it is a "nice to have" or sugar-coating feature. I think it would be useful for when you are dealing with long types, e.g.:
Lazy<List<MyNamespace.ISomeVeryLongInterfaceType>> myVar = obj.GetLazy();
it would be:
var myVar = obj.GetLazy();
This is much cleaner in my opinion. However, are there any objective arguments for OR against type inference? Is it good programming practice to use it, even in situations where it is arguable that it provides no benefit (e.g., using 'var' instead of 'int')?
Some help in understanding how I should use 'var' in my day-to-day coding would be great.
As nouns, the difference between disadvantage and advantage is that disadvantage is a weakness or undesirable characteristic; a con while the advantage is any condition, circumstance, opportunity, or means, particularly favorable to success, or any desired end.
ad·van·tage əd-ˈvan-tij. : superiority of position or condition. Higher ground gave the enemy the advantage. : a factor or circumstance of benefit to its possessor. lacked the advantages of an education.
Advantages vs. Benefits. Advantages explain the significance of a feature and how it solves a problem, often in a factual, concrete, or measurable way. Benefits, on the other hand, are subjective and appeal to the emotions or pains of the prospect.
Type inference was invented for exactly the reason you give for C++, you can create anonymous types that don't HAVE a type name (see Lambdas and Linq in particular).
So in that case it's needed.
In the other case (when the type name is known) then it comes down to style. I use var
when the type is really obvious:
// I like this - less duplication and easier to read
var item = new List<ComplexObjectItem>();
instead of:
List<ComplexObjectItem> item = new List<ComplexObjectItem>();
Because it reduces duplication.
However, I prefer not to use it when the type is not immediately obvious to the reader:
// I don't like this - I need to look up what the type is
var item = ResultOfSomeFunctionWhereICantSeeWhatItIs();
But your mileage might vary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With