From the Twitter…
karlseguin
dear c#…why new []{“it’s”, “over”, “9000”}; why not just [“it’s”, “over”, “9000”]; ??
The man makes a wonderful point. Karl jumped from the .NET ship a while back. He sought greener pastures in the Ruby playground.
We have the var keyword in C#, which tells us that C# is already type-inference aware. If I were to type…
var index = 2; var message = "Hello, World"; var value = 123.0; var payment = 456.78m;
… the compiler is plenty smart enough to know that I mean an integer, string, double, and decimal data type, respectively. We’ve had that since C# 3, and it’s wonderful.
There are some niceties in Ruby that should be portable to the C# type inference system. Why the need for the new keyword when the compiler should be smart enough to figure out types. The brackets are (almost) universal for arrays. This should work…
var stringArray = ["Hello", "World"]; var intArray = [1, 2, 3]; var pointArray = [new Point(0, 0), new Point(0, 10), new Point(10, 10), new Point(10, 0)];
Again, the types should easily be inferred as string[], int[], and Point[], respectively. Need a List<T> instead? No problem at all. Just add a .ToList() to the end of your array initializer and you’re set.
So how about something more difficult?
What would you do with something like this? Ruby has a hash (something C# devs would call a dictionary). Ruby can quickly build a hash (dictionary) in the following manner…
person = { "name" => "Jimmy", "age" => 7 }
It’s worth noting that C# would have to treat this as a Dictionary<string, object>. Ruby lets you mix and match because everything is an object.
Unfortunately, the best we can do in C# is this…
var person = new Dictionary<string, object> { { "name", "Jimmy" }, { "age", 7 } };
Wow, that’s a lot of typing! Let’s see how we can fix this. We already have the braces in C#, and we have anonymous objects, and this looks a lot like the building a hash in Ruby. So what if we had something really simple like the following. That would be nice, right?
var name = new { First = "John", Middle = "Q", Last = "Public" }.ToDictionary<string>();
As it turns out, this isn’t difficult to do.
public static class ObjectToDictionaryHelper
{
/// <summary>
/// Converts the given object to a dictionary based on its properties. The
/// dictionary keys will be strings matching the property names.
/// </summary>
public static IDictionary ToDictionary(this object source)
{
return source.ToDictionary
See? Not so bad at all. I’ve still got that new keyword sitting there. We should be able to get rid of that when creating an anonymous object. And converting the anonymous object to a dictionary is a fairly simple extension method. Now, I’ve just got to get some of the masterminds who write C# 5 to read my blog!
The source code for this post has been posted on GitHub.