Log in

Subscribe to site updates.

Faux Dictionary Literals in C# 3.0

Posted by Nicholas Blumhardt | September 18, 2007 10:23

Luke Marshall inspired this little, um, gem ;)

If you're enjoying the fresh, functional features in C# 3.0, you might be a little put out by the fact that you can't express dictionaries (maps in C++ parlance, hashes elsewhere) in a single expression. Arrays and lists both have a handy all-in-one initialisation expression so that you can write:

SomeFunction(new[]{ 1, 2, 3 });

Other languages support similar syntax for key-value pairs, e.g. Ruby:

some_function({ :name => 'Nick', :height => 185 })

You can omit the braces in many instances, and v.19 makes the syntax even more succinct.

Well, in C# 3.0 we're not completely out in the cold. There is the interesting new anonymous type declaration that lets us instantiate objects with particular properties in a single statement:

var me = new { Name = "Nick", Height = 185 };

There isn't much that we can tell about the object held in me except that it has the properties Name and Height.

This is enough, however, for an extension method called ToDictionary() to work some reflective miracles and turn our object into an IDictionary<string,object>...

var props = new { Name = "Nick", Height = 185 }.ToDictionary();

foreach (var prop in props)
	Console.WriteLine("{0} = {1}", prop.Key, prop.Value);

The code for the magical ToDictionary() method is below - and, it works on any object.

public static class ToDictionaryExtension
{
  public static IDictionary<string, object> ToDictionary(this object o)
  {
    if (o == null) throw new ArgumentNullException("o");
    var dict = new Dictionary<string, object>();
    foreach (PropertyInfo pi in o.GetType().GetProperties())
      dict[pi.Name] = pi.GetValue(o, null);
    return dict;
  }
}

Disclaimer - this code will make the ToDictionary() method available through every object used in your code - this is one of those abuses of the new extension method feature that you really shouldn't commit! I warned you! :)

Comments

C# Gems

Posted by Luke Marshall | September 20, 2007 19:32

Lookout, I'm a blog inspiration! :) Great article Nick.

Posted by Nicholas Blumhardt | September 21, 2007 04:12

I probably should remove your name to protect the (ahem) innocent... hehe

Luke's Blog ...

Posted by G|oS|co | October 10, 2007 16:42

Be sure to check out Luke's block "Math Geek Coder" on Blogspot mathgeekcoder.blogspot.com

Hello, my name is Gudvin, I like yours blog.

Posted by Hello, my name is Gudvin, I like yours blog. | November 12, 2007 19:58

Hello, my name is Gudvin, I like yours blog.

Dictionary Literals *are* in C#3!

Posted by Nicholas Blumhardt | December 20, 2007 05:49

The power of the type inferencer surprises me: var dict = new Dictionary<string,string>(){ { "A", "This is A" }, { "B", "A value for B" } }; This uses the fact that Dictionary implements Add() - the surprise comes from the fact that the KeyValuePair<string,string> item type is used to infer values from { k, v } pairs. Awesome!

Your Comment





Reset

Disclaimer: These articles represent the opinions of the authors and may not match the official position of Ubik Systems Pty. Ltd. Confirmation should be sought on all matters involving professional advice.