Everytime the program loads, I need a dictionary to have about 15 values. Right now I'm using a function called "Load_Dictionary" that just adds each value. How do you suggest going about loading a dictionary like this? Through a function? Using an XML file?
Make a static property of a class and in the get accessor have a check if the private static counterpart is null and if so build it else return it
[ThreadStatic]
private static Dictionary<string, string> _MyProperty;
public static Dictionary<string, string> MyProperty
{
get
{
return _MyProperty = _MyProperty ?? StaticFunctionToLoadValues();
}
}
Make a static readonly property/field and set it in the static constructor of the class.
public static readonly Dictionary<string, string> Field;
static Foo()
{
Field = new Dictionary<string, string>
{
{"key", "value"},
};
}
Or make an assignment right in the declaration:
public static readonly Dictionary<string, string> Field = new Dictionary<string, string>
{
{"key", "value"},
};
To get it initialised at the right point, I'd create a static private function returning a dictionary with the correct values, and use that as the member initialiser of a static field in the class:
class Foo
{
static Dictionary<string, string> makeDictionary()
{
return new Dictionary<string, string>
{
{"hello", "mum"},
};
}
static Dictionary<string, string> theDictionary = makeDictionary();
}
As for how to write that function, it really depends on the form of your data. This static initialiser style should probably be your first choice, unless there's a reason it doesn't work for you. Since you're writing the function, you can always add additional logic if you need it.
Note that in C# 3.0 you can use a collection initializer to initialize a static field, then you don't need your own constructor. Keep the data private and provide an access mechanism to avoid the need to synchronize the data (since it is only ever read):
private static readonly Dictionary<string, string> myData
= new Dictionary<string, string> {
{"abc","def"},
{"ghi","jkl"},
{"mno","pqr"},
};
public static string GetValue(string key) { return myData[key]; }
If you have lots of data to load, consider some kind of serialized form. Xml, binary, a database - whatever.