M
Marc Gravell
Given a generic method "of T", is there a good way of ensuring that any
static ctor on T has executed? Following code demonstrates (TestClass1)
that via generics you can use the Type instance long before the static
ctor fires.
With a generic class and the "new()" clause, I can force this in the
static ctor of the generic class, but this is not always convenient,
plus may (possibly?) be seen as a no-op [not sure here].
Sample; ideally I'd get "Static ctor 1" to output before the type-name
of 1 (as per the second test), without using any hacks...
Marc
using System;
class Prog {
static void Main() {
GenMethod<TestClass1>();
GenClass<TestClass2>.Method();
}
static void GenMethod<T>() {
Console.WriteLine("GenMethod" + typeof(T).FullName);
}
}
class GenClass<T> where T : new()
{
static GenClass() { // possibly set noinlining
new T(); // throw away; forces T's static ctor
}
public static void Method() {
Console.WriteLine("Method: " + typeof(T).FullName);
}
}
class TestClass1 {
static TestClass1() {
Console.WriteLine("Static ctor 1");
}
}
class TestClass2 {
static TestClass2() {
Console.WriteLine("Static ctor 2");
}
}
static ctor on T has executed? Following code demonstrates (TestClass1)
that via generics you can use the Type instance long before the static
ctor fires.
With a generic class and the "new()" clause, I can force this in the
static ctor of the generic class, but this is not always convenient,
plus may (possibly?) be seen as a no-op [not sure here].
Sample; ideally I'd get "Static ctor 1" to output before the type-name
of 1 (as per the second test), without using any hacks...
Marc
using System;
class Prog {
static void Main() {
GenMethod<TestClass1>();
GenClass<TestClass2>.Method();
}
static void GenMethod<T>() {
Console.WriteLine("GenMethod" + typeof(T).FullName);
}
}
class GenClass<T> where T : new()
{
static GenClass() { // possibly set noinlining
new T(); // throw away; forces T's static ctor
}
public static void Method() {
Console.WriteLine("Method: " + typeof(T).FullName);
}
}
class TestClass1 {
static TestClass1() {
Console.WriteLine("Static ctor 1");
}
}
class TestClass2 {
static TestClass2() {
Console.WriteLine("Static ctor 2");
}
}