Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a Java static block equivalent to a C# static constructor?

What is the real difference between a C# static constructor and a Java static block?

They both must be parameterless. They are both called only once, when the related class is first used.

Am I missing something, or are they the same thing, just with different names?

like image 592
Mackenzie Avatar asked Mar 17 '10 19:03

Mackenzie


People also ask

What is a static block in Java?

In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block. This is because it is an option for initializing or setting up the class at run-time.

Is it good to use static block in Java?

In other words, we can also say that static block always gets executed first in Java because it is stored in the memory at the time of class loading and before the object creation. Let's test which one is executed first by JVM, the static block, or static method with help of an example program.

Does C++ have static block?

A static block implementation for C++This is a single-header-file repository which allows for writing static blocks in C++. That is: Blocks of code, outside of any function, which can't be called from a function, and are executed once when the program starts (before main() ).

What is the advantage of static block?

Advantages of static blocksThe logic to be executed during the class loading before executing the main() method can be in a static block. Static blocks are mainly used to initialize the static variables.


2 Answers

They are equivalent, except that a C# class can only have one static constructor (plus static field initializers).

Also, in C#, a static constructor will apply the beforefieldinit flag.

like image 149
SLaks Avatar answered Sep 17 '22 18:09

SLaks


They look the same, the following example shows, that c# static constructor works the same as static block in java

protected Singleton()
{
    Console.WriteLine("Singleton constructor");
}

    private static readonly Singleton INSTANCE;

    static Singleton() {
        try {
           INSTANCE = new Singleton();
        }
        catch(Exception e) {
            throw new Exception();
        }
    }
like image 31
alexander Avatar answered Sep 18 '22 18:09

alexander