tags:

views:

263

answers:

2

In Java I can write:

public class Foo {

    public static Foo DEFAULT_FOO;

    static {
        DEFAULT_FOO = new Foo();
        // initialize 
        DEFAULT_FOO.init();
    }

    public Foo() {
    }

    void init() {
        // initialize
    }
}

How can I get the same functionailty in C# (where static members are initialized before use)? And, if this is a bad thing to try to do, what is a better approach?

+12  A: 

you use a static constructor, like this:

public class Foo
{
  static Foo()
  {
     // inits
  }
}

Here's more info.

Bottom line: it's a paramaterless constructor with the static keyword attached to it. Works just like the static block in Java.

Edit: One more thing to mention. If you just want to construct something statically, you can statically initialize a variable without the need for the static constructor. For example:

public class Foo
{
  public static Bar StaticBar = new Bar();
}

Keep in mind that you'll need a static constructor if you want to call any methods on Bar during static initialization, so your example that calls Foo.Init() still needs a static constructor. I'm just sayin' you're not limited, is all. :)

Randolpho
Wow! Thanks for incredibly speedy replies
peter.murray.rust
+1  A: 

Static is still the keywork in C#:

public class Foo {
    public static Foo DefaultFoo;

    static Foo {
        DefaultFoo = new Foo();
        // initialize 
        DefaultFoo.init();
    }

    public Foo() {
    }

    void init() {
        // initialize
    }
}
Reed Copsey