What is the use of static constructors?

203,469

Solution 1

No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.

It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).

Solution 2

From Static Constructors (C# Programming Guide):

A static constructor is used to initialize any static data, or to perform a particular action that needs 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:

  • A static constructor does not take access modifiers or have parameters.

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  • A static constructor cannot be called directly.

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

  • 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.

  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Solution 3

Static constructors are also very useful when you have static fields that rely upon each other such that the order of initialization is important. If you run your code through a formatter/beautifier that changes the order of the fields then you may find yourself with null values where you didn't expect them.

Example: Suppose we had this class:

class ScopeMonitor
{
    static string urlFragment = "foo/bar";
    static string firstPart= "http://www.example.com/";
    static string fullUrl= firstPart + urlFragment;
}

When you access fullUr, it will be "http://www.example.com/foo/bar".

Months later you're cleaning up your code and alphabetize the fields (let's say they're part of a much larger list, so you don't notice the problem). You have:

class ScopeMonitor
{
    static string firstPart= "http://www.example.com/";
    static string fullUrl= firstPart + urlFragment;
    static string urlFragment = "foo/bar";
}

Your fullUrl value is now just "http://www.example.com/" since urlFragment hadn't been initialized at the time fullUrl was being set. Not good. So, you add a static constructor to take care of the initialization:

class ScopeMonitor
{
    static string firstPart= "http://www.example.com/";
    static string fullUrl;
    static string urlFragment = "foo/bar";

    static ScopeMonitor()
    {
        fullUrl= firstPart + urlFragment;

    }
}

Now, no matter what order you have the fields, the initialization will always be correct.

Solution 4

1.It can only access the static member(s) of the class.

Reason : Non static member is specific to the object instance. If static constructor are allowed to work on non static members it will reflect the changes in all the object instance, which is impractical.

2.There should be no parameter(s) in static constructor.

Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it. 3.Only one static constructor is allowed.

Reason: Overloading needs the two methods to be different in terms of method/constructor definition which is not possible in static constructor.

4.There should be no access modifier to it.

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

Solution 5

you can use static constructor to initializes static fields. It runs at an indeterminate time before those fields are used. Microsoft's documentation and many developers warn that static constructors on a type impose a substantial overhead.
It is best to avoid static constructors for maximum performance.
update: you can't use more than one static constructor in the same class, however you can use other instance constructors with (maximum) one static constructor.

Share:
203,469
Dr. Rajesh Rolen
Author by

Dr. Rajesh Rolen

Over 15 years of successful experience in development of multi-tier applications and system integration solutions as application architect, project leader, technical lead, and software engineer. Very good understanding of application analysis and design concepts. Strong ability to apply proven design patterns to the system design and employ extreme programming and SCRUM techniques to the robust implementations. PhD (Computer Science & Engineering), MCA, BCA, MCTS, MCP, SCJP. Experience of working in the complete Software development life cycle involving SRS, Software architecture design, database design, Code Reviews, development, and documentation. Capable to delve into the new leading Technologies. Ability to work well in both a team environment and individual environment. Ability to train the team. Areas of Expertise Strong in Architecture design, Design Principles, Design Patterns and OOPs concepts. Capable of developing cross-platform code and managing project. Web applications and web services development using ASP.NET MVC with C#.NET/ VB.NET. Client-Server based applications developed using C#.NET and VB.NET Strong in Business requirement analysis and functional specification design and documentation. Through knowledge of Object Oriented Analysis and Design OOAD and N - Tier Architecture Strong in front-end GUI development using ASP.Net, HTML, JavaScript, JQuery. Strong in backend database development including designing and administering databases, - writing stored procedures, SQL and triggers for SQL Server, Oracle, and My-SQL databases. Strong Analytical Skills. Strong oral and written communication skills Download CV

Updated on February 14, 2022

Comments

  • Dr. Rajesh Rolen
    Dr. Rajesh Rolen over 2 years

    Please explain to me the use of static constructor. Why and when would we create a static constructor and is it possible to overload one?

  • Dr. Rajesh Rolen
    Dr. Rajesh Rolen over 13 years
    thanks for reply. can you please provide me more details about your sentence "Unless you abuse reflection, it is guaranteed to run at most once".. what can do with reflection regarding static constructor..
  • Marc Gravell
    Marc Gravell over 13 years
    @Rajesh - find the method and call Invoke 20 times.
  • Johnny_D
    Johnny_D about 11 years
    Hi @MarcGravell, please clarify what's the difference between CLR2 and CLR4 static constructors' behavior. And also, does it mean that static constructors are thread safe?
  • Marc Gravell
    Marc Gravell about 11 years
    @Johnny_D pretty sure there are conditions where they can be deferred later in CLR4 - the exact scenario would need some digging. Re thread-safe: in sane scenarios, yes - basically. If you abuse them with reflection: not so much
  • ruffin
    ruffin almost 7 years
    It may be exceptionally obvious, but I think this answer hits a key point only implicit in, eg, marc's answer -- Static constructors are not in lieu of instance constructors. They are called once, before the first instance is created, to set up static properties, etc. Instance constructors keep on working like they've always operated, setting up stuff particular to that instance. static constructor:static class concerns::instance constructor:instance level concerns Makes some sense. ;^)
  • Hardgraf
    Hardgraf over 6 years
    If you are using ReSharper then I believe it will warn you in this situation when attempting to set fullUrl before urlFragment has been initialised. Good example nonetheless.
  • Derreck Dean
    Derreck Dean almost 6 years
    For anyone interested how static constructor initialization changed from CLR 2 to CLR 4, Jon Skeet's blog post (codeblog.jonskeet.uk/2010/01/26/…) sums it up nicely: CLR 2 uses eager initialization, while CLR 4 uses lazy initialization.
  • NoChance
    NoChance almost 4 years
    Maybe the question should have ben what is the value of coding an static constructor. The compiler will take care of initializing static fields/properties any way without explicit coding of the constructor.
  • NoChance
    NoChance almost 4 years
    Do we know that the static constructor will execute after the field intialization every time? I guess not because Andrew's answer above says "A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.".
  • Mark Meuer
    Mark Meuer almost 4 years
    @NoChance Are you asking if the static constructor can be confident the fields that are initialized directly (in the example above firstPart and urlFragment) will have been initialized before that static constructor is called? The answer is yes, as long as the fields are listed before the static constructor. From MS docs: If static field variable initializers are present in the class of the static constructor, they will be executed in the textual order in which they appear in the class declaration immediately prior to the execution of the static constructor.
  • Mark Meuer
    Mark Meuer almost 4 years
    @NoChance Re-reading my comment, I believe I misspoke when I said the fields with initializers need to precede the static constructor. They will be initialized before the static constructor is executed regardless of where they are in the file.