C # static class, static constructor, static variable,

Source: Internet
Author: User

C # static class, static constructor, static variable,

This article describes static variables, static constructors, and static classes.

 

Static variables

Static variables are located on the stack. They are a global variable generated during the compilation period.

    public class Cow
    {
        public static int count;
        private int id;
 
        public Cow()
        {
            id = ++count;
        }
    }

 

The client creates two Cow instances and prints the static variable count.

        static void Main(string[] args)
        {
            Console.WriteLine(Cow.count);
            Cow cow1 = new Cow();
            Cow cow2 = new Cow();
            Console.WriteLine(Cow.count);
        }

Result:
0
2

○ The static variable count is available globally before the Cow instance is created.
○ If you use private modification before static, you cannot use "class name. static Field name" to access static fields. However, Global static fields always exist.

 

Stack and stack performance, such:

Static Constructor

Add a static constructor to the Cow class.

    public class Cow
    {
        public static int count;
        private int id;
 
        public Cow()
        {
            id = ++count;
        }
 
        static Cow()
        {
            count = new Random().Next(100);
        }
    }

 

Both constructors and static constructors assign values to Cow static fields. Now we want to know when the static constructor is triggered. Is it triggered when the constructor is used to create an instance? Will it be triggered when Cow fields or attribute values are set? On the client side, you can print the value of the static field count to know when the static constructor is triggered.

 

Static void Main (string [] args) {Cow cow1 = new Cow (); Console. writeLine ("after the first Cow instance is created, count is:" + Cow. count); Cow cow2 = new Cow (); Console. writeLine ("after the second Cow instance is created, count is:" + Cow. count );}
○ The static constructor is triggered when the first Cow instance is created.
○ When creating the second Cow instance, the static constructor is not triggered, but is used to create an instance.
○ The static constructor is executed only once.

 

Therefore, can we conclude that the static constructor is triggered when the first instance is created?

 

Let's think about this problem from another angle. Will a static constructor be triggered when assigning values to fields of the class?

 

Modify the Cow class:

 

    public class Cow
    {
        public static int count;
        private int id;
        public static int whatever;
        public Cow()
        {
            id = ++count;
        }
 
        static Cow()
        {
            count = new Random().Next(100);
            whatever = count + 10;
Console. WriteLine ("after the static constructor is triggered, count is:" + Cow. count );
Console. WriteLine ("after the static constructor is triggered, whatever is:" + Cow. whatever );
        }
    }

Modify the client:

 

        static void Main(string[] args)
        {
            Cow.count = 100;
            Cow cow1 = new Cow();
Console. WriteLine ("after the first Cow instance is created, count is:" + Cow. count );
            Cow cow2 = new Cow();
Console. WriteLine ("after the second Cow instance is created, count is:" + Cow. count );
        }

○ The static constructor is triggered before the Cow field is assigned a value.
○ Create a Cow instance. The static constructor will not be triggered again.
○ The static constructor is executed only once.

 

Here, we can draw a conclusion about the timing when the static constructor is triggered: whether it is creating an instance through the constructor or assigning values to fields or attributes of the class, static constructors are triggered before all these actions.

 

Static class

First, create a class, including static and non-static members.

    public class Logger
    {
        private static int logNumber = 0;
 
        static public void InitializeLogging()
        {
Console. WriteLine ("log initialization ");
        }
 
        static public void CloseLog()
        {
Console. WriteLine ("log disabled ");
        }
 
        static public void LogMsg(string msg)
        {
Console. WriteLine ("log number:" + logNumber + ":" + msg );
        }
 
        public void DoSth()
        {
Console. WriteLine ("I am not a static method ~~ ");
        }
    }

 

On the client, you can call a method either by using "class name. Static Method Name" or by using an instance of the class.

        static void Main(string[] args)
        {
            Logger.InitializeLogging();
Logger. LogMsg ("log recorded ~~ ");
            Logger.CloseLog();
 
            Logger logger = new Logger();
            logger.DoSth();
        }

 

If you set a class to a static class, it means that all of this class exists on the stack. Therefore, this class cannot contain instance methods or create such instances.

 

Modify the Logger class and remove the instance method.

    public static class Logger
    {
        private static int logNumber = 0;
 
        static public void InitializeLogging()
        {
Console. WriteLine ("log initialization ");
        }
 
        static public void CloseLog()
        {
Console. WriteLine ("log disabled ");
        }
 
        static public void LogMsg(string msg)
        {
Console. WriteLine ("log number:" + logNumber + ":" + msg );
        }
    }

 

On the client, you cannot create a Logger instance. You can only call a method by using "class name. Static Method Name.

        static void Main(string[] args)
        {
            Logger.InitializeLogging();
Logger. LogMsg ("log recorded ~~ ");
            Logger.CloseLog();
        }

 

 

Summary:
○ Static variables are global and on the stack
○ The static constructor is triggered only once. Whether you create an instance through the constructor or assign values to the fields or attributes of the class, the trigger time of the static constructor is before these actions.
○ The static class cannot contain instance members.

 

 

 

Related Article

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.