Friday, May 12, 2023

Static constructor in C#

 What is static constructor in C#?


In C#, a static constructor is a special type of constructor method that gets called automatically before the first instance of a class is created or before any static members of the class are accessed. The purpose of a static constructor is to initialize static data members or perform any other necessary setup operations that are related to the class itself rather than to any specific instance of the class.


A static constructor is declared using the "static" keyword and has no access modifiers. It does not take any parameters, and its name is always the same as the name of the class.


Here's an example of a static constructor:


```

class MyClass

{

    static int count;


    static MyClass()

    {

        Console.WriteLine("Static constructor called.");

        count = 0;

    }


    public MyClass()

    {

        count++;

    }


    public static int GetCount()

    {

        return count;

    }

}

```


In this example, the "MyClass" class has a static constructor that initializes the static "count" variable to zero. The constructor also prints a message to the console to indicate that it has been called.


The "MyClass" class also has a parameterless constructor that increments the "count" variable each time a new instance of the class is created. The class also provides a static method called "GetCount()" that returns the value of the "count" variable.


When the program runs and the "MyClass" type is first accessed, the static constructor is automatically called to initialize the "count" variable. The constructor is called only once, before any instance of the class is created or any static member is accessed.


Static constructors are useful for initializing static data members or performing other initialization tasks that are related to the class itself. They cannot be called explicitly and are automatically called by the runtime.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...