C# Static Constructor (with Examples)

A static constructor is a method that initializes static data members of a class or executes a specific task that needs to be done only once. This constructor is automatically invoked before the first instance of a class is created, or any static data members are accessed.

In this post, We will learn about the C# static constructor with multiple examples.

CSharp Static Constructor
C# Static Constructor

Syntax

The examples below will show you how to declare static constructor syntax without any parameters or access modifiers.

 // Creating a class
    public class Customer
    {
        // Creating a static constructor
        static Customer()
        {
            // Code that needs to be execute only once.
         }
    }
c# static constructor syntax
c# static constructor syntax

Characteristics of Static constructor in C#:

A static constructor in C# has the following characteristics.

CharacteristicDescription
Access Modifiers:A static constructor has no access modifiers and cannot be called directly.
Automatic Invocation:A static constructor is automatically called by the .NET runtime before the first instance of the class is created, or any static members are referenced.
Instantiation:A static constructor cannot be called using the new operator.
Parameters:A static constructor takes no arguments and cannot be parameterized.
Inheritance:A static constructor is not inherited and cannot be overridden.
Execution:A static constructor is only executed once per application domain, regardless of the number of instances of the class created.
Overloading:The static constructor never overloads because it does not accept any input parameters.
Quantity:A class or struct can have only one static constructor.
Naming:The name of a static constructor must be the same as the class or struct name.
Return Type:A static constructor has no return type, not even void.
Invocation Order:In C#, a static constructor is called before the Main() method.
Object-Independence:A static constructor is object-independent because it can be only called by the CLR and not by the developer.
Initialization:Non-static data members cannot be initialized in the static constructor.
Readonly Fields:A field declared static read-only could only be assigned during its declaration or in a static constructor.
Static Constructor in C#

C# Static constructor example

Following is an example of a static constructor in C#.

using System;
namespace StaticConstructorExample
{  
    // Customer class
    public class Customer
    {
       // Static Constructor
      static  Customer()
        {
            Console.WriteLine("Static constructor executed !");         
        }

        //Default constructor

       public Customer()
        {
            Console.WriteLine("Default constructor executed !");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
         // Here, Static and instance constructors
        // will invoke for the first instance

            Customer customer1 = new Customer();

          // Here only default constructor will invoke not the static constructor.
            Customer customer2 = new Customer();
            Console.ReadLine();
        } 
    }
    /* Output:
     Static constructor executed !
     Default constructor executed !
     Default constructor executed !
     */
}

Output:

The output of static constructor program in C#
The output of the above C# static constructor program.

In the above example, the Static constructor gets invoked only once at the time of the first object creation of the Customer class.
For the next object creation, only the default constructor will be called.

Note: If you don’t provide a static constructor in a class to initialize static fields or variables, the C# compiler will initialize static fields to default values.

5 Scenarios Where Static Constructors Are Useful in C#

Here are some scenarios where you might want to use a static constructor in C#:

  1. Initializing static fields or properties: You can use a static constructor to initialize static fields or properties of a class. It is useful when you have some values that need to be set before any instances of the class are created.
  2. Loading configuration files or resources: You can use a static constructor to load configuration files or other resources your class needs to function. It ensures that the resources are loaded before any instances of the class are created.
  3. Registering events or services: You can use a static constructor to register events or services your class needs to interact with. A static constructor can be useful when you want to ensure that these events or services are registered before any instances of the class are created.
  4. Enforcing class invariants: You can use a static constructor to enforce class invariants, such as ensuring that specific fields have valid values or that some constraints are met.
  5. Initializing unmanaged resources: You can use a static constructor to initialize unmanaged resources, such as opening a file or initializing a database connection. It ensures that the resources are available before any instances of the class are created.

Overall, static constructors are useful when you want to ensure that some initialization code is executed before any instances of a class are created.

FAQs

Following are some frequently asked questions and answers about Static constructor in C#:

Q: What is static constructor in C#?

A static constructor in C# is a special method that is called automatically when a class is first loaded into memory. It is used to initialize any static members of the class.

Q: Why static constructor is parameterless in C#?

There is no way to call a static constructor explicitly. Therefore, having a parameterized static constructor is pointless.

Q: Can we have static and default constructors in C# at the same time?

Yes, A non-static class can have both static as well as default constructors at the same time.

Q: Can a static constructor throw exceptions in C#?

Yes, a static constructor in C# can throw exceptions if an error occurs during initialization. For example, if a static constructor tries to read a file that does not exist, it may throw a FileNotFoundException.

Q: Can you call a static constructor explicitly in C#?

No, a static constructor in C# cannot be called explicitly. It is automatically called by the .NET runtime before the first instance of the class is created or any static members are referenced.

Q: When is a static constructor called in C#?

A static constructor is called automatically when the class is first accessed or when an instance is created.

Q: How is a static constructor different from an instance constructor in C#?

A static constructor is called automatically when the class is loaded into memory, whereas an instance constructor is called when an instance of the class is created. Also, a static constructor takes no parameters, whereas an instance constructor can take parameters.

Q: Can a static constructor have parameters in C#?

No, a static constructor in C# cannot have parameters.

Q: What can you do in a static constructor in C#?

In a static constructor in C#, you can initialize any static fields or properties of the class, load configuration files or resources, register events or services, enforce class invariants, and initialize unmanaged resources.

References MSDN: Constructors

Summary:

In this article, we learned about the static constructor in C# with examples. I hope you enjoyed this post and found it useful. In case you have any doubts, please post your feedback, question, or comments below.

Articles to Check Out

Shekh Ali
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments