Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 375
Graviton Avatar asked Nov 24 '08 03:11

Graviton


People also ask

How to declare static dictionary 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" } };

What is a static dictionary?

adjective Also stat·i·cal . pertaining to or characterized by a fixed or stationary condition. showing little or no change: a static concept; a static relationship. lacking movement, development, or vitality: The novel was marred by static characterizations, especially in its central figures. Sociology.

How do I create a static dictionary in Python?

Create Dictionaries Just combine all the “key1:value1, key2:value2,…” pairs and enclose with curly braces. The combination of a key and its value, i.e. “key: value” represents a single element of a dictionary in Python. While defining static dictionary objects, you must be careful to use unique values for keys.


1 Answers

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.

like image 112
Yona Avatar answered Sep 28 '22 11:09

Yona