what is the c# equivalent of static {...} in Java?
c#, java, static
Solution
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. :)
Problem
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?