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".
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" } };
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With