Tuesday 4 March 2014

Posted by Prasad KM | 08:51 Categories:

Static Constructor in C#

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  1. A static constructor does not take access modifiers or have parameters or it will not support to access modifiers.
  2. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  3. A Static constructor executing Opposite direction of normal constructors.
  4. A static constructor cannot be called directly.
  5. The user has no control on when the static constructor is executed in the program.
  6. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  7. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the Load Library method.
  8. If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.\

Example :

    public class ClassA
    {
      
        public ClassA()
        {}
        static ClassA()
        { }

     }

    public class ClassB : ClassA
    {
        static ClassB()
        { }

        public ClassB()
        { }
    }


 Main function :


ClassB instance =new ClassB()
Executing Steps

1. Static constructor in ClassB.
2. Static constructor in ClassA.
3. Public constructor in ClassA.
4 Public constructor in ClassB.





0 comments:

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube