c# – Declare a dictionary inside a static class

c# – Declare a dictionary inside a static class

If you want to declare the dictionary once and never change it then declare it as readonly:

private static readonly Dictionary<string, string> ErrorCodes
    = new Dictionary<string, string>
{
    { 1, Error One },
    { 2, Error Two }
};

If you want to dictionary items to be readonly (not just the reference but also the items in the collection) then you will have to create a readonly dictionary class that implements IDictionary.

Check out ReadOnlyCollection for reference.

BTW const can only be used when declaring scalar values inline.

The correct syntax ( as tested in VS 2008 SP1), is this:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic;
     static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {1, User name or password problem} };
    }
}

c# – Declare a dictionary inside a static class

Old question, but I found this useful. Turns out, theres also a specialized class for a Dictionary using a string for both the key and the value:

private static readonly StringDictionary SegmentSyntaxErrorCodes = new StringDictionary
{
    { 1, Unrecognized segment ID },
    { 2, Unexpected segment }
};

Edit: Per Chriss comment below, using Dictionary<string, string> over StringDictionary is generally preferred but will depend on your situation. If youre dealing with an older code base, you might be limited to the StringDictionary. Also, note that the following line:

myDict[foo]

will return null if myDict is a StringDictionary, but an exception will be thrown in case of Dictionary<string, string>. See the SO post he mentioned for more information, which is the source of this edit.

Leave a Reply

Your email address will not be published.