5

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.

Community
  • 1
  • 1
Fontanka16
  • 1,161
  • 1
  • 9
  • 37

2 Answers2

1

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)
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 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
-1

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>.

Simon
  • 9,255
  • 4
  • 37
  • 54
  • 5
    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