Wednesday, September 13, 2017

Static Constructor in C#

Static constructor is a special constructor that gets called before the first object of the class is created. It is used to initialize any static data, or to perform a particular action that needs performed once only.
The time of execution of static constructor is not known but it is definitely before the first object creation - may be at the time of loading assembly.
  1. public class MyStaticClass
  2. {
  3. static int count;
  4. static MyStaticClass()
  5. {
  6. count = 0;
  7. Console.WriteLine("Static class is initialized");
  8. }
  9. It can only access the static member(s) of the class.
  10. There should be no parameter(s) in static constructor, therefore static constructor overloading not possible.
    Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it.
  11. There should be no access modifier to it.
  12. Reason: Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it
    1. using System;
    2. public Class question {
    3. static question()
    4. {
    5. //initialize static member only.
    6. }
    7. public question()
    8. {
    9. // codes for the first derive class constructor.
    10. }
    11. }

    12. Yes, this is perfectly valid even if it doesn't match with the rule of overloading concept. The only reason of being it valid is that the time of execution of the two constructors are different, (i) static question() at the time of loading the assembly and (ii) public question() at the time of creating object.

No comments:

Post a Comment