Understanding C # static constructor through a pen question

Source: Internet
Author: User

Today I saw a C # pen question about static fields and static constructor initialization. Static functions are a new feature of C #. If you do not know the initialization sequence, you will be confused about this question. For static constructors, see http://www.cnblogs.com/michaelxu/archive/2007/03/29/693401.html. Analyze the initialization sequence of the static constructor from this question.

1 class A <br/> 2 {<br/> 3 Public static int X; <br/> 4 static () <br/> 5 {<br/> 6 x = B .y + 1; <br/> 7} <br/> 8} <br/> 9 class B <br/> 10 {<br/> 11 public static int y = a.x + 1; <br/> 12 static B () {}< br/> 13 static void main () <br/> 14 {<br/> 15 console. writeline ("x = {0}, y = {1}", a.x, B .y); <br/> 16} <br/> 17} <br/>

What is the output result?

1. Call the main function first. It is the static method of B. When any static member of a class is called for the first time, the static constructor is called, before that, you need to allocate memory for the static field y in B and execute the code 11th lines.

2. When the first step of execution calls the static member X of A, it triggers the call of the static constructor of A. When the code is executed in line 6th, the static field y of B appears again in this line, because y has not been initialized, the default value is 0, so this row x = 1

3. After running the static constructor A, return to row 11th, and y = 2.

4. After running the static constructor B, return to main and execute line 4 of the Code to print a.x and B .y. The result is unknown.

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.