开发者

What exactly are Static Constructor in 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

publi开发者_JAVA百科c 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


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;
    }
}


You use them the same way you use instance constructors - to set default values. Only in this case you'll be initializing static fields, so static constructors get executed only once.

Be aware that the code in static constructor won't be executed until the first call to the class was made.


it runs when class is loaded.

It will print : {

  1. hi from static A
  2. A

}

public class A{
  static A{
     print("hi from static A");
  }

  public A() {
    print("A");
  }

  main() {
      new A();
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜