[c#] Declare a dictionary inside a static class

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".

This question is related to c# .net dictionary

The answer is


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.


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

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.


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#.


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.


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

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#.


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

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.


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

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.


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#.


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.


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

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.


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.


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.


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#.


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

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.


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.


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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python