I have a static class with a static list property on. I want to generate the content of the list only once, and then be able to use it. I of course also want to ensure that the data is actually created so that when an object uses the class it has data in the list. How do I accomplish this?
public static class MyClass
{
public static List<int> MyList = new List<int>();
public MyClass()
{
for (int i = 0; i < 10; i++)
{
MyList.Add(i);
}
}
}
Your current code ensures exactly that, when you change the constructor to a static one:
The class loader will execute the initialization of
MyListbefore any other member of the class can be executed. This happens the first time the class is used.The observable behaviour is that the static members are initalized (once) at the beginning of your application.
Only when you build something where static initializers depend on each other you may have something to think/worry about.