user1017882
user1017882

Reputation:

static readonly Dictionary<> declared anonymously

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.

Upvotes: 0

Views: 850

Answers (2)

Adam Houldsworth
Adam Houldsworth

Reputation: 64477

No, it is not impossible. Using collection initializers, it would look like this:

Dictionary<Guid, string> idsAndStrings = new Dictionary<Guid, string>
{
    { Guid.NewGuid(), "" },
    { Guid.NewGuid(), "" },
};

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.

Upvotes: 2

Jon
Jon

Reputation: 437336

Your existing syntax looks correct, so the only part that could have an error are the Guid or string constants.

If you are attempting to pass in the Guids as strings, use the appropriate Guid constructor explicitly:

{ new Guid("XXX-XXX"), "string" },
{ new Guid("YYY-YYY"), "string" },

Upvotes: 1

Related Questions