How to declare a static dictionary object inside a static class? I tried
public static class ErrorCode
{
public const IDictionary E
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.
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.
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#.
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.