I have a problem with static initialization when I follow a Singleton approach and I don't understand what is going on here. Target framework is 4.5. This is a brand new project. Did not modify any settings.
Here I made a sample of the offending code, the expected result is that "Static Value" should appear on the console. However, nothing appears. Debugging in fact shows that at the time of Console.Write the static variable Static_Value is null.
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Test MyClass = Test.Instance;
Console.ReadKey();
}
}
class Test
{
public static Test _instance = new Test();
public static Test Instance
{
get { return _instance; }
}
public static readonly string Static_Value = "Static Value";
static Test()
{
}
private Test()
{
Console.Write(Static_Value + Environment.NewLine);
}
}
}
if I drop the singleton approach instead, it works.
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Test MyClass = new Test();
Console.ReadKey();
}
}
class Test
{
public static Test _instance = new Test();
public static Test Instance
{
get { return _instance; }
}
public static readonly string Static_Value = "Static Value";
public Test()
{
Console.Write(Static_Value + Environment.NewLine);
}
}
}
I am definitely puzzled on what is going on here. Aren't static variables initialized the first time they are accessed? Because it doesnt't seem to be happening....
Can anyone shed some light here?
EDIT:
following René Vogt hint I modified my code according to the standard, and it now works. As all static initializers side effect are accounted when the static constructor runs, I moved the initialization of the _instance to the static constructor, which will anyway run before the getter of Instance runs.
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Test MyClass = Test.Instance;
Console.ReadKey();
}
}
class Test
{
private static Test _instance;
public static Test Instance
{
get { return _instance; }
}
public static readonly string Static_Value = "Static Value";
static Test()
{
_instance = new Test();
}
private Test()
{
Console.Write(Static_Value + Environment.NewLine);
}
}
}