Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly are Static Constructor in C#?

Tags:

c#

I have couple of question regarding Static Constructor in C#.

  1. What exactly are Static Constructor and how they are different from non-static Constructor.
  2. How can we use them in our application ?

**Edited

public class Test
{
    // Static constructor:
    static Test()
    {
        Console.WriteLine("Static constructor invoked.");
    }

    public static void TestMethod()
    {
       Console.WriteLine("TestMethod invoked.");
    }
}

class Sample
{
    static void Main()
    {
        Test.TestMethod();
    }
}

Output : Static constructor invoked. TestMethod invoked. So, this means that static constructor will be called once. if we again call Test.TestMethod(); static constructor won't invoke.


Any pointer or suggestion would be appreciated '

Thanks

like image 297
Shaitender Singh Avatar asked Dec 03 '25 09:12

Shaitender Singh


1 Answers

Static constructors are constructors that are executed only ONCE when the class is loaded. Regular (non-static) constructors are executed every time an object is created.

Take a look at this example:

public class A
{
     public static int aStaticVal;
     public int aVal;

     static A() {
         aStaticVal = 50;
     }

     public A() {
         aVal = aStaticVal++;
     }
}

And consider this code:

A a1 = new A();
A a2 = new A();
A a3 = new A();

Here, static constructor will be called first and only once during the execution of the program. While regular constructor will be called three times (once for each object instantiation).

static constructors are usually used to do initialization of static fields for example, assigning an initial value to static fields.. Do keep in mind that you will only be able to access static members (methods, properties and fields) on static constructors.

If you need to "execute the static constructor multiple times", you can't do that. Instead, you can put the code you want to run "multiple times" in a static method and call it whenever you need. Something like:

public class A {
    public static int a, b;
    static A() {
         A.ResetStaticVariables();
    }
    public static void ResetStaticVariables() {
        a = b = 0;
    }
}
like image 140
Pablo Santa Cruz Avatar answered Dec 05 '25 22:12

Pablo Santa Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!