C # Learning static Constructor

Source: Internet
Author: User
  1. Using system;
  2. Class circle
  3. {
  4. Private int R;
  5. Public circle ()
  6. {
  7. Console. writeline ("nonstatic ");
  8. }
  9. Static circle ()
  10. {
  11. Console. writeline ("static ");
  12. }
  13. Public static void main ()
  14. {
  15. Console. writeline ("1st line ");
  16. Circle X, Y; // 1st rows
  17. Console. writeline ("2nd line ");
  18. X = new circle (); // 2nd rows
  19. Console. writeline ("3rd line ");
  20. Y = new circle (); // 3rd rows
  21. }
  22. }

Description of static constructor:

(1) It is used to initialize static and read-only fields.
(2) You cannot add access modifiers when adding static keywords because static constructors are private.
(3) Static constructor of a class can be executed at most once in a given application domain: only the static constructor of the class is activated when an instance of the class is created or any static member of the referenced class is activated.
(4) Static constructors cannot be inherited and cannot be called directly.
(5) If the class contains the main method used to start execution, the static constructor of the class will be executed before calling the main method. For any static field with an initial value, the initial values must be executed in the text order before executing the static constructor of this class.
(6) If a static constructor is not compiled, and the class contains a static field with an initial value, the compiler automatically generates the default static constructor.

 

The program that starts with (5) knows and outputs the result:
Static
1st line
2nd Line
Nonstatic
3rd line
Nonstatic

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.