I have a class with static properties. I want this class to have a static, read only dictionary – and I want to initialize it anonymously. I’ve tried the following but it doesn’t work:
public static readonly Guid ID1 = new Guid("53ba029b-0850-4f51-a358-648411e30972");
public static readonly Guid ID2 = new Guid("400a9861-21c3-45fd-bf75-95be8f535c58");
public static readonly Dictionary<Guid, String> IdsAndStrings = new Dictionary<Guid, string>(){
{ID1, "string"},
{ID2, "string 2"}
};
I’m getting an exception when trying to initialize this. The inner exception even mentions incorrect conversion to datetime!? Not sure what’s going on there. Is it impossible to instance a new Dictionary<> like this? Should I be using Get Set instead?
EDIT: Please assume all guids and strings are valid.
No, it is not impossible. Using collection initializers, it would look like this:
Get/set would expose the item as a writable property, which is semantically different to a readonly field – it will offer different behaviour in some cases.