【. NET pose with "const and readonly initialization posture

Source: Internet
Author: User

Using System;     Class P {static readonly int a=b*10;        static readonly int b=10;     public static void Main (string[] args) {Console.WriteLine ("A was {0},b is {1}", A, b); } }

For the above code, what is the output? A lot of people would think it was a 100,b is 10! In fact, the correct output result is A was 0,b is 10. Well, if you change to the following:

Using System;     Class P {const int a=b*10;        const int b=10;     public static void Main (string[] args) {Console.WriteLine ("A was {0},b is {1}", A, b); } }

For the above code, how much output is the result? Is it 0,b is 10? In fact, it is wrong, this time the correct output is a was 100,b is 10.

So why is that so? In fact, the above said, const is a static constant, so at compile time will be a and B value down (that is, b variable 10, and a=b*10=10*10=100), then the output of the main function is of course A is 100,b is 10. The static readonly is a dynamic constant, the value of the variable is not parsed during compilation, so the start is the default value, like A and B are int type, ancient capital is 0. And in the execution of the program to A=B*10, so a=0*10=0, the program then executes to b=10 this sentence, only real B's initial value 10 is assigned to B.

【. NET pose with "const and readonly initialization posture

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.