I am currently working on refactoring some code, where I have stumbled upon this static
dictionary:
public static Dictionary<string, string> CountryNamesAndCodes()
{
var dictionary = new Dictionary<string, string>();
dictionary.Add("AF", "Afghanistan");
dictionary.Add("AL", "Albania");
dictionary.Add("DZ", "Algeria");
dictionary.Add("AD", "Andorra");
dictionary.Add("AO", "Angola");
dictionary.Add("AG", "Antigua and Barbuda");
dictionary.Add("AR", "Argentina");
dictionary.Add("AM", "Armenia");
...
}
Which first of all is defined in the service layer, and takes up a lot a space - 400
lines, and eventhough it is static
, it seem to always recreate the dictionary, meaning making the static part of it redundant - or am I wrong?
how do I ensure that this is only created once, and everytime I call it, it make use of the same instance.
CodePudding user response:
You are quite right, you can extract the local dictionary as a static member
I suggest something like this (field):
// static readonly (we want to create it once) field of
// IReadOnlyDictionary type - we want to read key value pairs after its creation
private static readonly IReadOnlyDictionary<string, string> countries =
// We may want to be nice and let ignore case for keys
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{ "AF", "Afghanistan" },
{ "AL", "Albania" },
{ "DZ", "Algeria" },
//TODO:Put all the other records here
};
or like this (property):
// static readonly (there's no "set") property of
// IReadOnlyDictionary type - we want just to read key value pairs after its creation
private static IReadOnlyDictionary<string, string> Countries { get; } =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{ "AF", "Afghanistan" },
{ "AL", "Albania" },
{ "DZ", "Algeria" },
//TODO:Put all the other records here
};
CodePudding user response:
public static class Globals
{
static Dictionary<string, string>
CountryNamesAndCodes = new Dictionary<string, string>
{
{"AF", "Afghanistan"},
{"AL", "Albania"}
};
}
name = Globals.CountryNamesAndCodes["AF"];