About C # compiler guaranteed variables must initialize rules conjecture

Source: Internet
Author: User

There are two situations:

First case:

usingSystem;namespacewrox{ Public classProgram {Static voidMain (string[] args) {            intindex; if(true) {Index= -;                        } Console.WriteLine (index);                    Console.readkey (); }    }}

Second case:

usingSystem;namespacewrox{ Public classProgram {Static voidMain (string[] args) {            intindex; BOOLIstrue=true; if(IsTrue = =true) {Index= -;                        } Console.WriteLine (index);                    Console.readkey (); }    }}

In both cases, the first case compiles normally, and the second fails to compile, prompting the index variable to be uninitialized.

The reason for this individual guess analysis is as follows:

In the first case, when the compiler executes to the IF statement, because true is a constant, it can be judged at compile time that the branch of the index initialization will go, so the compilation succeeds.

In the second case, when the compiler executes to the IF statement, because IsTrue is a variable, the compiler cannot get its value at this point. Therefore, the compiler is used to determine whether the index is initialized or not, to determine if all the branches that might be overwritten are initialized with the index variable. Because the index is only initialized in the if branch at this time, an error is compiled at this point.

To verify the above inference, the code can be modified as follows:

usingSystem;namespacewrox{ Public classProgram {Static voidMain (string[] args) {            intindex; Const BOOLIstrue=true; if(IsTrue = =true) {Index= -;                        } Console.WriteLine (index);                    Console.readkey (); }    }}

The above code is compiled correctly, so this inference can be supported.

About C # compiler guaranteed variables must initialize rules conjecture

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.