Creating a constant Dictionary in C#


What is the most efficient way to create a constant (never changes at runtime) mapping of strings to ints?

I've tried using a const Dictionary, but that didn't work out.

I could implement a immutable wrapper with appropriate semantics, but that still doesn't seem totally right.

For those who have asked, I'm implementing IDataErrorInfo in a generated class and am looking for a way to make the columnName lookup into my array of descriptors.

I wasn't aware (typo when testing! d'oh!) that switch accepts strings, so that's what I'm gonna use. Thanks!

4/11/2018 12:17:50 PM

Accepted Answer

Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.

There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:

switch (myString)
   case "cat": return 0;
   case "dog": return 1;
   case "elephant": return 3;

This is exactly what you want. And yes, I know, it's ugly.

4/18/2010 4:58:22 PM

Exper Answer

There are precious few immutable collections in the current framework. I can think of one relatively pain-free option in .NET 3.5:

Use Enumerable.ToLookup() - the Lookup<,> class is immutable (but multi-valued on the rhs); you can do this from a Dictionary<,> quite easily:

    Dictionary<string, int> ids = new Dictionary<string, int> {
      {"abc",1}, {"def",2}, {"ghi",3}
    ILookup<string, int> lookup = ids.ToLookup(x => x.Key, x => x.Value);
    int i = lookup["def"].Single();
11/6/2008 9:51:32 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow