Here is a program that does not trigger some static constructors though it displays distinct owned static instances.
class Program
{
static void Main(string[] args)
{
Template.Render();
Template2.Render();
Console.WriteLine(ReferenceEquals(Template.Factory, Template2.Factory));
}
}
public class BaseTemplate<T> where T : new()
{
static BaseTemplate()
{
Console.WriteLine("BaseTemplate() " + typeof(T).Name);
}
public static object Factory = new object();
public static void Render()
{
Console.WriteLine("Render() from " + typeof(T).Name);
}
}
public class Template : BaseTemplate<Template>
{
static Template()
{
Console.WriteLine("Static ctor()");
}
}
public class Template2 : BaseTemplate<Template2>
{
static Template2()
{
Console.WriteLine("Static ctor() 2");
}
}
The result
BaseTemplate() Template
Render() from Template
BaseTemplate() Template2
Render() from Template2
False
The goal here is to have a custom instance of Factory
for each sub-class, which works fine, but also to initialize it in a static constructor. We can see the Factory
instances are distinct from the reference test, but the static constructors are not called unless specifically called with System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle);
Then the result is the following.
Static ctor()
BaseTemplate() Template
Render() from Template
Static ctor() 2
BaseTemplate() Template2
Render() from Template2
False