Set Dictionary to constant

Asked

Viewed 51 times

1

Follow the code below:

var values = new Dictionary<string, string>
{
    { "tipo1", "dada65d" },
    { "tipo2", "546541354765321" },
    { "tipo3", "klwoiqyhalwtbfowh" }
};

How can I declare the class Dictionary as constant (const)?

  • 1

    It would be nice if it could be const even, but I know the limitations of the CLR and the gain would not be so great.

2 answers

2

I left another alternative using readonly

private readonly static Dictionary<string, string> values = new Dictionary<string, string>()
{
    { "tipo1", "dada65d" },
    { "tipo2", "546541354765321" },
    { "tipo3", "klwoiqyhalwtbfowh" }
};

1

For these cases I usually use an Enum, because it is, in a certain way, a constant dictionary.

But anyway you can use readonly so that it is only written in the constructor and not elsewhere.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.