Take the 2-minute tour ×

In my solution i depend heavily on Dictionaries with an enum as a key. I find it is easy to understand and to read this construction.

One significant obstacle to the above is that it is not possible to serialize this. See Problems with Json Serialize Dictionary<Enum, Int32> for more info on this.

My question is:
Is there a equally readable and intuitive pattern for replacing the Dictionary<enunm,object> that is json serializable with the built in json serializer?

Today I have replaced a.Instance.QueryableFields[Fields.Title] with a.Instance.QueryableFields[ Fields.Title.ToString()] . Not very elegant, and it is opening up for errors.

share|improve this question
Is the enum a property on your object being stored as the value of the dictionary? I might suggest using the enum value as a hash code in that case. –  Brannon Mar 17 '12 at 16:24
How would that work? Could you point me to an example? –  Fontanka16 Mar 17 '12 at 20:31
add comment

2 Answers

When serializing it, just select the string value. It's not very neat, but it works.

a.Instance.QueryableFields.ToDictionary(x => x.Key.ToString(), x => x.Value)
share|improve this answer
It is an option i have cosidered. But then i have to write my own serialize method. Thank you for the suggestion, but i am looking for a way to replace the entire thing. Either the dictionary or the enum. –  Fontanka16 Mar 17 '12 at 20:28
add comment

You can easily replace a dictionary with an array here, as in C# Enums are internally saved as integers:

public enum MyEnum { Zero=0, One, Two };

object[] dictionary = new object[3];
dictionary[(int)MyEnum.Zero] = 4;

EDIT: (see comments)

You can also replace Dictionary<Enum, Object> with Dictionary<Int, Object>.

share|improve this answer
This has sense only if you're sure that values go from 0 to array.Length-1 without any break. If you have an enum like {A=0, B=42, C=31415} you should create an array of 31416 elements... –  digEmAll Mar 17 '12 at 14:41
add comment

Your Answer


