Static Constructor in C# and their Usages

Let's start with constructor definition.Constructor is a special method of a class that is  invoked automatically whenever a new instance/object of class is created.Constructors are responsible for object initialization and memory allocation for all class members. A class without constructor does't mean that it  has no constructor .Compiler will automatically create a default constructor for that class.
Static constructor

Static constructor in C#If we declare a constructor as static then it will be invoked only once.It means that it doesn't matter that how many instances you create, static constructor will fire only once on first reference creation.

Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.



Here are some important point about static constructor -
  1. Static constructor of a class executes before any instance of the class is created.
  2. Static constructor of a class executes before any of the static members for the class are referenced.
  3. Static constructor of a class executes after the static field initializes.
  4. Static constructor of a class executes only once.
  5. Static constructor does not have any access modifiers or have parameters.
  6. Static constructor cannot be called explicitly.
  7. User has no control on when the static constructor is executed in the program. 

Hope you have like this tutorial.


Thanks.

Static Constructor in C# and their Usages Static Constructor in C# and their Usages Reviewed by CodiBucket on 02:32 Rating: 5

No comments:

Facebook

Powered by Blogger.