[Study again] Static Constructor

Source: Internet
Author: User
The static constructor can be used in C # to initialize class data in the same way as the instance constructor used to initialize instance data. There are some differences between static constructor and instance constructor rules. Unlike the instance constructor, static constructor cannot be overloaded, so only one default non-parameter static constructor is available for static constructor. Static constructors cannot be explicitly called or inherited from the derived class, but can be called when a base class type is created.
C # principles for using static constructor:
1. The static constructor is called before the class instance is created. Therefore, it is called before all instance constructor instances.
2. The static constructor is called before the first instance of the class is created.
3. The static constructor is called before a static field is referenced.
The following is a simple example. Class Test
{
Static Test ()
{
Console. writeline ("");
}

Public test ()
{
Console. writeline ("B ");
}
}
Class test1: Test
{
Public test1 ()
{
Console. writeline ("C ");
}
}

Test T = new test () during instantiation ();
Test T1 = new test ();
Test1 t2 = new test1 ();

Output: A, B, B, B, c
The static constructor is called only once.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.