Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the c# equivalent of static {...} in Java?

Tags:

java

c#

static

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?

like image 887
peter.murray.rust Avatar asked Jul 29 '09 18:07

peter.murray.rust


People also ask

What is C used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language in simple words?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.

What is this C language?

C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.


1 Answers

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. :)

like image 163
Randolpho Avatar answered Sep 21 '22 04:09

Randolpho