Print

The constructor conflict

Sometimes I'm wondering strange things. For instance, this morning I was wondering if a static constructor of a class can create an instance of itself. It seemed to me this would be a conflicting requirement, because a classes constructor will only run after it's static constructor has run.

A little test proves that it is actually completely valid.

class A
{
static int x;

static A()
{
// Create an instance of A
A a = new A();

a.X = 3;
}

public A() { }

public int X
{
get { return x; }
set { x = value; }
}
}

This code snippet compiles and runs fine. So actually, a non-static constructor of a class can run during and after the execution of the static constructor.

- C# - two comments / No trackbacks - §

The code samples on my weblog are colorized using javascript, but you disabled javascript (for my website) on your browser. If you're interested in viewing the posted code snippets in color, please enable javascript.

two comments:

This is an old post, but what the hell...

My understanding of static constructors was you couldn't guarantee when they were run, but they were always run beforeyou called a static method or property. Therefore calling a constructor, as above is valid, because the static constructor and class constructors don't have any dependancies on each other.

In fact, the above is a fine pattern for a singleton. just make the class constructor private.
Simon - 19 05 10 - 18:06

That's a good point.
Steven (URL) - 19 05 10 - 23:38


No trackbacks:

Trackback link:

Please enable javascript to generate a trackback url


  
Remember personal info?

/

Before sending a comment, you have to answer correctly a simple question everyone knows the answer to. This completely baffles automated spam bots.
 

  (Register your username / Log in)

Notify:
Hide email:

Small print: All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.