How to (lamely) create a map in C#

time to read 4 min | 798 words

There are a lot of cases where I need to define in code some sort of a map that I would later want to modify. This is usually as simple as mapping a static list to be used in the code. This about mapping from System.Type to SqlType, for instance.

This is something that javascript can do very easily, and one of the reasons that I really like Boo. Check this out:

typeToSqlType = {

       System.Int32 : System.Data.SqlTypes.SqlInt32

       System.Int64 : System.Data.SqlTypes.SqlInt64

}

I am using those types of lists all over the place. In C#, you are forced to use a hashtable or a dictionary and manually create it. Bummer. Well, I gave it some though, and it looks like C# does support this syntax, although it is pretty aweful.

Type[][] typesToSqlType =

      {

        new Type[]{typeof(System.Int32), typeof(System.Data.SqlTypes.SqlInt32)},

        new Type[]{typeof(System.Int32), typeof(System.Data.SqlTypes.SqlInt32)}

      };

I will spare you what I have to do when it require different types of parameters. What is scary is that this is still more readable that the normal way to do this in C#