C # static Constructor

Source: Internet
Author: User

"Static constructor" is typically used for initialization when the class is used for the first time. Note that "the first time" means that it is executed only once. Some people have said, isn't class initialization a constructor? A constructor is executed when an instance is declared. It belongs to every instance, but the static constructor belongs to this class. For example, the number of students enrolled in 2013 is "13xxxx ". Therefore, the initial value 13xxxx is a common sacrifice of this student group, not a student. Student IDs and names are all unique attributes of a student. According to the characteristics that the static constructor only executes once, the school student management system writes the "130001" number in a configuration file, and the school management system immediately reads the number as soon as it runs, look at the management system. Oh, let me start from 130001! When writing code, let's first create a student class

Class Student {// first create an attribute for this class: the starting Student ID private static int _ startNumber; // The static constructor is used to read the Starting number set in the configuration file or database. Static Student () {_ startNumber = 130001; // assume that we read the 130001} // Student ID field private int _ code from the configuration file; // Student ID attribute public int Code {get {return _ code;} set {_ code = value ;}// the Student ID increases by 1 public Student () each time an instance object is attached () {this. _ code = (_ startNumber ++ );}

 

Let's try two students:
class Program      {          static void Main(string[] args)          {              Student s1 = new Student();              Console.WriteLine(s1.Code);                Student s2 = new Student();              Console.WriteLine(s2.Code);          }      }  

 

Result: 130001130002

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.