A static function is used to initialise any static data or to make a single-use action. Before the first instance is created or any static members are accessed, it is automatically called.
Points to remember about Static Constructor:
- There are no access modifiers or arguments in a static function.
- There can only be one static function per class or struct.
- Inherited or overloaded constructors are not allowed.
- A static function can only be invoked by the common language runtime and cannot be called directly (CLR). It’s started on its own.
- The user has no control over when the program’s static function is called.
- In a single application domain, the runtime invokes a static function no more than once. A static function is called automatically.
- If you don’t provide a static function to initialise them, all static fields are set to their default value.
- If a static function throws an exception, the runtime does not recall it, and the type stays uninitialized throughout the application domain.
- Because there is a static function, the BeforeFieldInit type attribute cannot be added. This limits the amount of time that can be optimised while running.
- Only as part of their declaration or in a static function may static read-only fields be assigned.
- The runtime only calls the static function once in a single application domain.
namespace StaticConstructor
{
class Addition
{
static Addition()
{
Console.WriteLine("Static Constructor called");
}
public Addition()
{
Console.WriteLine("Instance Constructor called");
}
}
class Program
{
static int Main(string[] args)
{
Addition obj1 = new Addition();
Addition obj2 = new Addition();
return 0;
}
}
}
Output:
Static Constructor called
Instance Constructor called
Instance Constructor called