Search code examples
c#inheritancestatic-constructor

c# static constructor not called from derived class


class Bus<T>
{
    static Bus()
    {
        foreach(FieldInfo fi in typeof(T).GetFields())
        {
            if(fi.FieldType == typeof(Argument))
            {
                fi.SetValue(typeof(T), new Argument("busyname", "busyvalue"));
            }
        }
    }
}
class Buss : Bus<Buss>
{
    public static Argument field;
}

Any ideas how to make this work so that a reference to the static field in Buss triggers the static constructor in Bus?


Solution

  • The fact that this matters to you probably means that you are using static constructors wrong.

    With that in mind, you could make a static constructor in Buss that manually invokes the static constructor in Bus. Note that it's not possible to run a static constructor more than once.