Apr 15 2009
Hitting the Limits of C#
I’ve resisted the urge of learning a dynamic language like F# or Ruby for a while but it’s hard to ignore that the deeper you go into c# the more it gets in your way. In the last 2 days I’ve had 2 problems in c# that simply wouldn’t have existed in a dynamic language.
First problem I had was needing to assign multiple values to an object property but I wouldn’t know the type of the value until runtime. The property was an int, but I could potentially assign a decimal or a long depending on what was returned from the underlying data source. Because c# requires static typing I had no choice but to choose an int as the property type and then do a bunch of crazy casting to handle the various runtime issues. In a dynamic language, I’d just assign the values and the type would be inferred.
The second problem I had involved variance with generic collections. The situation was that I had an interface called IParcel which was implemented by two classes, Disposal and Parcel. I also had a function that accepted as a parameter IList<IParcel>. The problem was that I couldn’t pass an IList<Disposal> or IList<Parcel> to the function even tho Disposal and Parcel derive from IParcel and therefore should be considered perfectly valid. Instead I had to call ConvertAll() on the collections to convert them to IList<IParcel> objects and then pass the converted list to the parameter. In a dynamic language, I would just pass either list into the collection and life would go on.
Variance is being addressed in c# 4.0 but it’s only one circumstance where these sorts of problems begin to hit the limit of what c# can do.
It will be interesting to see what direction Microsoft takes with C# and dynamic languages. It seems that they’re looking to accommodate dynamic typing within C# as much as possible but where pure functional programming is required they’re pushing people to F#. This makes good sense but I wonder if the lines will become blurred by allowing easier access to F# from directly within C#.
Whatever they do, I don’t think I’ll be making a full blown switch to a functional language soon but I’ll be watching what happens in this space as there is definitely room for some interesting solutions to these interesting problems.
