What is the use of static constructors?

C#ConstructorStatic Constructor

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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 - C#

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 - C#

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.

Solution 6 - C#

> Why and when would we create a static constructor ...?

One specific reason to use a static constructor is to create a 'super enum' class. Here's a (simple, contrived) example:

public class Animals
{
    private readonly string _description;
    private readonly string _speciesBinomialName;

    public string Description { get { return _description; } }
    public string SpeciesBinomialName { get { return _speciesBinomialName; } }
    
    private Animals(string description, string speciesBinomialName)
    {
        _description = description;
        _speciesBinomialName = speciesBinomialName;
    }

    private static readonly Animals _dog;
    private static readonly Animals _cat;
    private static readonly Animals _boaConstrictor;

    public static Animals Dog { get { return _dog; } }
    public static Animals Cat { get { return _cat; } }
    public static Animals BoaConstrictor { get { return _boaConstrictor; } }

    static Animals()
    {
        _dog = new Animals("Man's best friend", "Canis familiaris");
        _cat = new Animals("Small, typically furry, killer", "Felis catus");
        _boaConstrictor = new Animals("Large, heavy-bodied snake", "Boa constrictor");
    }
}

You'd use it very similarly (in syntactical appearance) to any other enum:

Animals.Dog

The advantage of this over a regular enum is that you can encapsulate related info easily. One disadvantage is that you can't use these values in a switch statement (because it requires constant values).

Solution 7 - C#

Static constructor called only the first instance of the class created. and used to perform a particular action that needs to be performed only once in the life cycle of the class.

Solution 8 - C#

From Microsoft documentation https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

Static Constructors (C# Programming Guide)

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

class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

Remarks

Static constructors have the following properties:

  • A static constructor doesn't take access modifiers or have parameters.
  • A class or struct can only have one static constructor.
  • Static constructors cannot be inherited or overloaded.
  • A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.
  • The user has no control on when the static constructor is executed in the program.
  • A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced. A static constructor runs before an instance constructor. A type's static constructor is called when a static method assigned to an event or a delegate is invoked and not when it is assigned. If static field variable initializers are present in the class of the static constructor, they're executed in the textual order in which they appear in the class declaration. The initializers run immediately prior to the execution of the static constructor.
  • If you don't provide a static constructor to initialize static fields, all static fields are initialized to their default value as listed in Default values of C# types.
  • If a static constructor throws an exception, the runtime doesn't invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain. Most commonly, a exception is thrown when a static constructor is unable to instantiate a type or for an unhandled exception occurring within a static constructor. For static constructors that aren't explicitly defined in source code, troubleshooting may require inspection of the intermediate language (IL) code.
  • The presence of a static constructor prevents the addition of the type attribute. This limits runtime optimization.
  • A field declared as static readonly may only be assigned as part of its declaration or in a static constructor. When an explicit static constructor isn't required, initialize static fields at declaration rather than through a static constructor for better runtime optimization.
  • The runtime calls a static constructor no more than once in a single application domain. That call is made in a locked region based on the specific type of the class. No additional locking mechanisms are needed in the body of a static constructor. To avoid the risk of deadlocks, don't block the current thread in static constructors and initializers. For example, don't wait on tasks, threads, wait handles or events, don't acquire locks, and don't execute blocking parallel operations such as parallel loops, Parallel.Invoke and Parallel LINQ queries.

> [!Note] > Though not directly accessible, the presence of an explicit static constructor should be documented to assist with troubleshooting initialization exceptions.

Usage
  • 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.
  • Static constructors are also a convenient place to enforce run-time checks on the type parameter that cannot be checked at compile time via type-parameter constraints.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDr. Rajesh RolenView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#Adriaan StanderView Answer on Stackoverflow
Solution 3 - C#Mark MeuerView Answer on Stackoverflow
Solution 4 - C#ravithejagView Answer on Stackoverflow
Solution 5 - C#Dot FreelancerView Answer on Stackoverflow
Solution 6 - C#Kenny EvittView Answer on Stackoverflow
Solution 7 - C#Hasan FathiView Answer on Stackoverflow
Solution 8 - C#JomaView Answer on Stackoverflow