C # static Static constructor

Source: Internet
Author: User

Static constructor,

1, for the initialization of static data

2, the preceding cannot have the parameter cannot have the modifier, cannot be called

Class program    {        private static  int count = 0;        static program ()          {             console.writeline ("I'm a static constructor, I'm loaded!") ");            count++;             console.writeline (count);         }        public program ()          {             Console.WriteLine ("I'm a public constructor, I'm loaded!") ");            count++;         }       &nbsP;static void main (String[] args)         {             program o1 = new program ();// Here two constructors call             console.writeline ("------- ---");             program o2 = new  program ();//Call only the second constructor              Console.WriteLine (count);             console.read ( );        }    }         /*  code Run Results:         I'm a static constructor, I'm loaded!     1     I'm a public constructor, I'm loaded!     ----------     I'm a public constructor, I'm loaded!     3        */ 


There is no access modifier in front of the constructor, the default is public, if you change to a modifier such as private and protected is not possible, because private access can only make this class, This means that if an object outside of this class is to be instantiated, the other is not.


C # static Static constructor

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.