Reputation: 621
The output of the following program is
base init
BaseMethod
derived init
DerivedMethod
Eg, the call to the base method from the derived class triggers the Base class's init stub and not the same of the Derived class.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Derived.BaseMethod());
Console.WriteLine(Derived.DerivedMethod());
}
}
class Base
{
public static string BaseMethod() { return "BaseMethod"; }
static bool init = InitClass();
static bool InitClass()
{
Console.WriteLine("base init");
return true;
}
}
class Derived : Base
{
public static string DerivedMethod() { return "DerivedMethod"; }
static bool init = InitClass();
static bool InitClass()
{
Console.WriteLine("derived init");
return true;
}
}
In reality, my base class has no initialization needs, but my derived class does, and I'd like to ensure that it's run before anyone interacts with the class in any way. Unfortunately, most of the interaction with it is via methods defined in the base class as per the example above.
I can alter the Derived class to hide the BaseMethod as follows:
class Derived : Base
{
public static new string BaseMethod() { return Base.BaseMethod(); }
public static string DerivedMethod() { return "DerivedMethod"; }
static bool init = InitClass();
static new bool InitClass()
{
Console.WriteLine("derived init");
return true;
}
}
And this produces the desired result of initializing the derived class on the call to Derived.BaseMethod(), but it isn't very satisfying since it's meaningless 'routing' code that would have to do be done for every public static base method.
Any suggestions?
Upvotes: 1
Views: 426
Reputation: 2443
instead of the derived class using static new bool InitClass()
, why not use a standard static constructor?
static bool init = false;
static Derived()
{
Console.WriteLine("derived init");
init = true;
}
Upvotes: 2