In the following code segment, I reference FILE_LOCATION
from outside this class, and after execution flows into this class to access that constant, for some reason instead of continuing back to the location where the constant call was made, execution continues to instantiate the singleton.
My question is two parts; why is this happening and how can I work around it? I tried to create two partial classes, one solely for the constant and another for everything else, but execution still continued to the other partial class to instantiate the singleton.
public sealed class Foo
{
public static readonly string FILE_LOCATION = @"path\to\file";
// (singleton code modeled after:
// http://csharpindepth.com/articles/general/singleton.aspx --fourth version)
private static readonly Foo foo = new Foo();
// Rest of class implementation...
}
The property is referenced from an instance of a form class on a button click:
public partial class MyForm : Form
{
public void button1_Click(object sender, EventArgs e)
{
string s = Foo.FILE_LOCATION;
// this location is only reached AFTER the singleton is instantiated.
}
}
To answer your questions in order,
FILE_LOCATION
, then all the static variable initializers run (including foo
). After that, the static constructor runs. Since there is no explicit static constructor, nothing is done here. Then your code runs. The reason this occurs is that sometimes the value of a static variable might be initialized depending on another static variable, so it's required to initialize them all at the same time.public static readonly string FILE_LOCATION
you can declare it as public const string FILE_LOCATION
. The value of a const is determined at compile-time and not at run-time, and so the static variable foo
will not be initialized when you access the FILE_LOCATION
. This can work if you can determine the value of the file location at compile-time; is that something you can do in your application?