Declare a dictionary inside a static class

C#.NetDictionary

C# Problem Overview


How to declare a static dictionary object inside a static class? I tried

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

But the compiler complains that "A const field of a reference type other than string can only be initialized with null".

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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"} };
    }
}

Solution 3 - C#

Old question, but I found this useful. Turns out, there's 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 Chris's comment below, using Dictionary<string, string> over StringDictionary is generally preferred but will depend on your situation. If you're 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.

Solution 4 - C#

> Create a static constructor to add values in the Dictionary

enum Commands
{
    StudentDetail
}
public static class Quires
{
    public static Dictionary<Commands, String> quire
        = new Dictionary<Commands, String>();
    static Quires()
    {
        quire.add(Commands.StudentDetail,@"SELECT * FROM student_b");
    }
}

Solution 5 - C#

The problem with your initial example was primarily due to the use of const rather than static; you can't create a non-null const reference in C#.

I believe this would also have worked:

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

Also, as Y Low points out, adding readonly is a good idea as well, and none of the modifiers discussed here will prevent the dictionary itself from being modified.

Solution 6 - C#

You can use the static/class constructor to initialize your dictionary:

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

Solution 7 - C#

Make the Dictionary a static, and never add to it outside of your static object's ctor. That seems to be a simpler solution than fiddling with the static/const rules in C#.

Solution 8 - C#

OK - so I'm working in ASP 2.x (not my choice...but hey who's bitching?).

None of the initialize Dictionary examples would work. Then I came across this: http://kozmic.pl/archive/2008/03/13/framework-tips-viii-initializing-dictionaries-and-collections.aspx

...which hipped me to the fact that one can't use collections initialization in ASP 2.x.

Solution 9 - C#

Use a public static property dictionary and wrap the static private dictionary inside. Then you only need to take care about mutable or immutable types, first one you need to iterate inside the wrapper. That allows you to read a dictionary, but not edit it (not the entries and not the whole reference) with the option to allow edit inside the set{} part using any authentication model you prefer.

(I was looking for something different, like static performance in parallel coding, saw this search result and find the wrapper approach missing.)

For those who don't know what wrapping is, here a non static example (you can easily add the static key-word):

public Dictionary<string, Boolean> Access
{
    get
    {
        // Same here, iterate if needed..
        return new Dictionary<string, Boolean>(prv_Access);
    }
    set
    {
        MainWindow.NewSession.Renew();
        if (MainWindow.NewSession.Actual)
        {
            prv_HistoryAccess.Add(DateTime.Now, new Dictionary<string, Boolean>(prv_Access));

            // Here you would need to iterate when you deal with mutables..
            prv_Access = value;
        }
    }
}

Solution 10 - C#

public static class ErrorCode
{
    public const IDictionary<string , string > m_ErrorCodeDic;

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

Probably initialise in the constructor.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGravitonView Question on Stackoverflow
Solution 1 - C#YonaView Answer on Stackoverflow
Solution 2 - C#GravitonView Answer on Stackoverflow
Solution 3 - C#areylingView Answer on Stackoverflow
Solution 4 - C#Sujith RadhakrishnanView Answer on Stackoverflow
Solution 5 - C#CharlieView Answer on Stackoverflow
Solution 6 - C#AndyView Answer on Stackoverflow
Solution 7 - C#Jeff HubbardView Answer on Stackoverflow
Solution 8 - C#jrayView Answer on Stackoverflow
Solution 9 - C#DororoView Answer on Stackoverflow
Solution 10 - C#CraigView Answer on Stackoverflow