static constructor in derived class not being called

  • Thread starter Elia Karagiannis
  • Start date
E

Elia Karagiannis

The static constructor of a derived class never gets called if it has no
other methods and the base class is only static

I have the following base class and derived class.

public class MyBase
{
protected MyBase()
{}

protected static int x;

public static void DoSomething()
{
Console.WriteLine("X = " + x.ToString());
}
}


// the derived class
public class MyDerived : MyBase
{
static MyDerived()
{
x = 5;
}
}

static void Main()
{
MyDerived.DoSomething(); // prints out zero instead of 5
// the static
constructor on the derived class never gets called
// if I add a dummy
static method to the derived class and call it then the
// static
constructor of the derived class will be called but I cant do this...
}


Any suggestions or can this just not be done??
 
O

Octavio Hernandez

Elia,

Interesting stuff!

My guess is:
a) Before the call to MyDerived.DoSomething(), the CLR loads MyDerived and
immediately executes static constructor
b) Because of the inheritance relationship, the CLR loads MyBase, and
immediately initializes static field to 0 and then executes static
constructor (which in this case does nothing).
c) The call to DoSomething() proceeds, printing 0...

Regards - Octavio
 
O

Oliver Sturm

Elia said:
Any suggestions or can this just not be done??

I guess this is as intended. The description in the C# language specs
(http://tinyurl.com/8wlg5) says:

----------------------- snip --------------------------
The execution of a static constructor is triggered by the first of the
following events to occur within an application domain:

* An instance of the class is created.
* Any of the static members of the class are referenced.
----------------------- snip --------------------------

Now, the problem here is that while you call the static method on the
class MyDerived, it's still not a "static member of the class", at least
not of *that* class.

Although that sounds confusing given the fact that it's possible to call
the base class static method via the derived class, I'm quite sure
that's how .NET sees it.


Oliver Sturm
 
O

Octavio Hernandez

Sorry,

I thought DoSomething was defined in MyDerived...
Now I think I agree with Oliver.

Regards - Octavio
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top