| Servergeek |
| Mickey Williams' weblog |
|
My C# BookMicrosoft Press PageOn Amazon Racing LinksSlalomSkateboarder.comNCDSA slalom page 3dm Ick Sticks Pocket Pistols .NETScott GuthrieRob Howard .NET Notes BradA LonghornScobleChris Sells ServicesDon BoxChristian Weyer All Things Distributed Ingo Rammer Tim Ewald BlawgsBag and BaggageSCOTUS Blog EconArg MaxCapital Spectator OtherWilliam Gibson |
Friday, September 16, 2005
A few thoughts on var and anonymous types in C# 3.0Posted 10:28 AMNow that generics are becoming more prevalent in C# programming, a common C++ issue starts to rear its head: the really long declaration. Consider: Dictionary<IdentitySlot<Person>, List<Paystubs>> emp2Paystubs = new Dictionary<IdentitySlot<Person>, List<Paystubs>>(); Think about it -- in the general case, the compiler knows what the type of emp2Paystubs should be. Although you might want the variable to be typed as a base type, in the majority of cases the type on the left-hand side matches the right-hand value. In C# 3.0, shown at PDC05, the compiler can simplify your declaration in the most common case, allowing you to specify var as the type: var emp2Paystubs = new Dictionary<IdentitySlot<Person>, List<Paystubs>>(); As a side note, var also helps eliminate the need for the dreaded typedef in C/C++. As a footnote to the side note, if you don't dread the typedef and are urgently demanding its return, perhaps now would be a good time to point out the recently improved syntax for mangaged C++ in Visual C++ 2005. It has typedef, and it's now much easier to use C++ for writing managed code. You're welcome. The rest of you should be using Eiffel for your second language. Keep in mind that var is really just some compiler magic over existing types: A var declaration can only be used as a local variable - it can't appear as a member, parameter, or return type. This enables the compiler to always assign a known type in the IL emitted during compilation, without you actually whispering the type name to the compiler. Further, in a number of scenarios such as when projecting an anonymous Linq type, you don't even know the name of the type. Consider this Linq fragment:
var q = from ord in db.Orders,
prod in db.products
where ord.OrderID == prod.OrderID
select new{ord, prod};
What is the type of q? Although the compiler can certainly assign a type name (perhaps something memorable such as __ilAeizneKeneR), it certainly is not discoverable prior to compilation (although it is available through reflection). It turns out that var enables you to use instances of these anonymous types in a simplified manner. The alternative would be to force you to artificially concoct a name for the type, even though it really isn't important to any actors in the drama, except for several portions of the compiler. More in another post.
|