I’ve encountered code with setup like this:
internal class Something
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
internal static class Factory
{
public static string Name { get; set; }
public static Something Create()
{
return new Something { Name = Name };
}
}
internal static class Resources
{
public static readonly Something DefaultSomething = Factory.Create();
}
internal class Program
{
public static void Main(string[] args)
{
Factory.Name = "MyFactory";
Execute();
Console.ReadKey();
}
private static void Execute()
{
Console.WriteLine(Resources.DefaultSomething);
}
}
Of course this is only a snippet and I’d like not to go into details why this is done this way.
My problem with this is the difference in behavior while running in debug and in release without debugger:
- debug or release with debugger:
MyFactoryis printed to console - release without debugger: empty line is printed
Obviously the issue is with order of execution of static elements initializes and some optimization that is done while compiling in release mode. I’d like to know how to fix this without braking this setup.
The fix is to add a static constructor to the Resources class:
EDIT Read this article by Jon Skeet