Welcome to WebmasterServe!

FREE TO JOIN! Join us now to engage in informative and friendly discussions about Webmastering, SEO, SEM, Internet Marketing, Programming, Graphic Design, Online Jobs and more. What are you waiting for? Ready to join our friendly community? It takes just one minute to register.

Dismiss Notice

Join WebmasterServe Forums 
Join the discussion! Have a better idea or an opinion? It takes just one minute to register Click Here to Join

What is a static constructors?

Discussion in '.NET Programming' started by beingchinmay, Sep 25, 2015.

  1. beingchinmay

    beingchinmay New Member

    Jun 4, 2015
    +0 / -0
    1. Special constructor and gets called before the first object is created of the class.
    2. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly.
    3. Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize
    4. them in the same way it can optimize inline assignments.
    5. The static constructor for a class executes before any of the static members for the class are referenced.
    6. The static constructor for a class executes after the static field initializers (if any) for the class.
    7. A static constructor cannot be called directly.
    8. The user has no control on when the static constructor is executed in the program.
    9. Example - When the class is using a log file and the
  2. Oldwriter

    Yellow Belt

    Dec 10, 2015
    +28 / -0
    Hello beingchinmay, regarding #8:

    "The user has no control on when the static constructor is executed in the program."

    If you are using a static class as a way to have exactly one instance of a class and want to have full control regarding your constructor's execution time, you may want to use the singleton pattern instead:

    Select All
    // Your singleton class public sealed class BeingchinmayClass { // Guaranteed unique instance static readonly BeingchinmayClass singletonInstance = new BeingchinmayClass(); // Singleton instance getter public static BeingchinmayClass GetInstance { get { return singletonInstance; } } // Constructor private BeingchinmayClass() { // Initialize your class members here. } }
    Then in your program's entry-point, instantiate your class in order to be 100% sure your constructor executes and relevant members are initialized before using it.

    Select All
    [STAThread] private static void Main(string[] args) { // Instantiate your singleton BeingchinmayClass beingchinmayClass = BeingchinmayClass.GetInstance; // Your program's regular code }
    Hope it helps.
    • Informative Informative x 1
    • List

Share This Page