What Inferred Types in C# 3.0 are Not!
Posted: Saturday, September 24, 2005 2:06 PM
by
bruce
Filed under: General Rants, Orcas
I had the opportunity earlier this week to listen on a MSDN chat covering the enhancements to C# that were unveiled at PDC. Listen being an imprecise term given that it was a chat, you understand.
I had two main takeaways from the chat. First, there was a ton of interest in LINQ and the various inner and outer workings of that. I’ll post some observations on that shortly. The second thing I learned was that there seemed to be a high level of confusion over exactly what inferred types are bringing to the table. I think that the real problem is that they don’t bring nearly as much as people expect/want/are afraid of. Please allow me to put the underlying thought into my own words.
In its simplest form, an inferred type looks like the following:
var a = 1;
The ‘var’ keyword is used in place of a data type. At compile time, it is inferred that a is intended to be an integer. From that point forward, the compile treats a as if it had been defined as:
int a = 1;
So much for the simplest case. And, in fact, using this as the example is a bit of a problem because no one should ever write code this way. In this simple a case, you should use the second code rather than the first. This makes it difficult to understand when inferred types are even useful. So let me pull the example that was used in the chat:
Dictionary>> peopleOrders = new Dictionary>>();
Now everyone who thinks this is easy to read hold up your hand. In this blog, where there is no syntax coloration, it’s hard to figure out what the name of the variable is, much less what the type is. When this code is read, the programmer will have to give it a second or third glance to get what is going on. And since variable declarations are not normally that important to the business logic of a method, all this syntax does is add friction to the process of understanding. So consider the inferred version:
var peopleOrders = new Dictionary>>();
Isn’t this much easier to digest? I’m sure that even those people who put their hands up for that last question will agree. At that, ultimately, is the purpose for inferred types. To reduce the friction involved in reading code. Strong typing is still in place. Programs are still type-safe. Casting exceptions will still be thrown when appropriate. In other words, inferred types are just a way to pretty up the syntax of C#. And given some of the code that I’ve looked in the past, anything that helps keep modules cleaner is worth it.
If you would like to receive an email when updates are made to this post, please register here