Static constructor in C# is used for assigning static fields.Static constructor is also used for performing tasks which needs to be performed only once.
Static constructor differs from normal constructors is several ways:
- You can not access static constructor explicitly
- It is automatically called after the object has been created and before any static field is accessed
- You can not define access modifier on a static constructor
- Static constructor is parameterless
- There can be only one static constructor in a class
Unlike normal constructors static constructors are called only once by the runtime and can not be called through code.We can not guarantee when a static constructor will run.All that is guaranteed is that the static constructor will run before any class member is accessed.It is possible to have a parameterless instance constructor and a static constructor in the same class.
In the following example we have defined a static constructor in a class called Employee
public class Employee { static readonly string organization; static Employee() { organization="IBM"; } }
If you try to declare access modifier on the static constructor then you will get compile time error.