Sunday, January 6, 2008

Misunderestimating C# 3.0

Dare Obasanjo, who's posts on C-Omega I've enjoyed very much in the past, has written a new article called Does C# 3.0 Beat Dynamic Languages at their Own Game? He does a good job of pointing out the way that C# 3.0 adds features commonly associated with Dynamic Languages (tuples, adding methods to existing classes) without abandoning static typing.

Unfortunately he misses the mark with his criticism of type inference. Take a look at his code sample:

Look at the portion highlighted in red. Dare laments that he cannot write new {Weight = voteFunc(item), Item=item, FeedTitle = feedTitle } and must instead create a Vote class. The reason for this is that he is adding votes to a List and to instantiate this list he must parameterize the generic List with the Vote type.

Now let's rewrite that code snippet using the idioms of C# 3.0:

I wrote the ToProjectedDictionaryOfLists function. It is an extension method on IEnumerable<T> and it accepts two lambda functions. One that accepts an item in the stream and returns a key for the dictionary and another that accepts an item in the stream and converts it into a different representation ("projects" it). Using these functions, a key and value is derived for each item in the stream. This information is used to populate the dictionary with lists of items that share the same key value.

It's important to notice four things about our replacement code:

1. We've specified no type information (type inference in full effect)
2. We've liberated the code that moves the data into a hash table from the code that creates the code.
3. We've abstracted the action of creating a dictionary of lists from a stream of data into a reusable function.
4. We've expressed the problem in such a way that it can be trivially parallelized.

In previous blog posts I mused that Linq's superficial similarity to SQL might keep developers from realizing how widely applicable it is. Dare mentions Linq in the article but fails to recognize that he could use it to improve his example code in every measure.

This is really about functional programming vs. imperative programming. Because of its inherent advantages developers should always try and solve a problem functionally first and fall back to imperative solutions only where the result is more readable. In C# a functional solution was rarely more readable because the language lacked the idioms to support it. C# 3.0 makes huge strides in this area. This should have a profound effect on the way you code. If your C# 3.0 code looks like your C# 2.0 with "var" statements and the occasional Linq query against a database you've got to some remedial reading to do. :-) Trust me, you'll be glad you did.

Here is the code for the ToProjectedDictionaryOfLists function:


Anonymous said...

That's a rather complicated solution to the problem. Ian Griffiths provided a simpler, more idiomatic solution using LINQ which I blogged about in a subsequent post at

Jafar Husain said...

I agree. Much better. I should have focused on what you were trying to do rather than rewrite a snippet. Readers are encouraged to follow that link.

Anonymous said...

Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my site, it is about the CresceNet, I hope you enjoy. The address is . A hug.

Anonymous said...

Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the Celular, I hope you enjoy. The address is A hug.

Anonymous said...

ugg bootsTHE SNOW wholesale ugg bootsSTARTED TO FALLWholesale handbags SEVERAL HOURS wholesale clothingBEFORE HER laborWholesale jewelry began.wholesale clothing A few flakes wholesale handbagsfirst, wholesale furniturein the dull Furniture Wholesalegray late-afternoon Wholesale jewelrysky,Ceramic tileand then Micro sd cardswind-driven swirls Wholesale clothingand eddies Wholesale Jewelryaround the edges Wholesale fashion jewelryof their wide Wholesale costume jewelryfront porch. ugg bootsHe stood by her wholesaleside at the windowwholesale electronics, watching sharp gusts of snow billow,skin care products
then swirl and drift to the ground. All around the neighborhood, lights came on, and the naked branches of the trees turned white.

Anonymous said...

ugg bootsOutside,uggs snow continuedHigh pressure blower to fall quietly throughIndustrial fan the darkness, Industrial bloweras bright and thick Commercial bloweras static in the wholesalecones of light castchina wholesale by the streetlights.wholesale shoes By the time he rosewholesale clothing and looked out watchesthe window, pressure blowertheir car had become a soft white hill on the edge pressure blowersof the Already his footprints blowers
in the driveway had filled and disappeared.

Anonymous said...

wholesaleShe looked up, wholesale atvsmiling, wedding dresseswhen he tuckedMP3 player
the blanketwholesale mp3 around her legs.Wholesale Mp4
"You know,digital camera wholesale I've been wondering consumer electronicswhat it's like,"mp5 player she said. memory cards"Before we're born,Car video players I mean. It's too bad we can't remember." gps devicesShe opened her robe and pulled up the bluetooth headsetsweater she wore underneath, revealing a Mp3 Wholesalebelly as round and hard asMp3 Wholesale a melon. Mp4 WholesaleShe ran her hand across its smooth surface, Mp4 Wholesalefirelight playing across her skin, casting reddish gold onto her hair.

Anonymous said...

cheap wedding gownsdiscount bridal gownsChina wedding dressesChina wedding online storediscount designer wedding dresses

Affordable Luxurious Wedding Dress Blog said...

cheap wedding gowns,
discount bridal gowns,
China wedding dresses,
discount designer wedding dresses,
China wedding online store,
plus size wedding dresses,
cheap informal wedding dresses,
junior bridesmaid dresses,
cheap bridesmaid dresses,
maternity bridesmaid dresses,
discount flower girl gowns,
cheap prom dresses,
party dresses,
evening dresses,
mother of the bride dresses,
special occasion dresses,
cheap quinceanera dresses,
hot red wedding dresses

Anonymous said...

China Wholesale has been described as the world’s factory. This phenomenom is typified by the rise ofbusiness. Incredible range of products available with China Wholesalers “Low Price and High Quality” not only reaches directly to their target clients worldwide but also ensures that wholesale from china from China means margins you cannot find elsewhere and buy products wholesaleChina Wholesale will skyroket your profits.

Anonymous said...

Women’s nike tn Shox Rivalry est le modèle féminin le plus tendance de baskets pour le sport. tn chaussuresConcernant la semelle :Cheap Brand Jeans ShopMen Jeans - True Religion Jeans nike shoes & Puma Shoes Online- tn nike, le caoutchouc extérieur, l’EVA intermédiaire et le textile intérieur s’associent pour attribuer à la.ed hardy shirts pretty fitCharlestoncheap columbia jackets. turned a pair of double plays to do the trick.Lacoste Polo Shirts, , Burberry Polo Shirts.wholesale Lacoste polo shirts and cheap polo shirtswith great price.Thank you so much!!cheap polo shirts men'ssweate,gillette mach3 razor bladesfor men.As for

Anonymous said...


About Me

My photo
I'm a software developer who started programming at age 16 and never saw any reason to stop. I'm working on the Presentation Platform Controls team at Microsoft. My primary interests are functional programming, and Rich Internet Applications.