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?
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.
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.
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() ).
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With