(original) C # learning note 06--function 02--variable scope 01--other structures

Source: Internet
Author: User
Tags variable scope

6.2 Scope of variables

In the previous section, readers may wonder why they need to exchange data using functions. The reason is that variables in C # can only be accessed from the local scope of the code. Given a variable has a scope, access to that variable is implemented by this scope.

In the previous section, readers may wonder why they need to exchange data using functions. The reason is that variables in C # can only be accessed from the local scope of the code. Given a variable has a scope, access to that variable is implemented by this scope. The code is as follows:

class Program {     staticvoid  Write ()     {         Console.WriteLine ("  MyString = {0}", myString);     }      Static void Main (string[] args)     {         string"string defined in Main () ";         Write ();         Console.readkey ();     } }

Compile the code, and note the errors and warnings that appear in the Task list:

The name ' myString ', '   myString'   in' is not present in the current context myString' is is never used "

What's wrong with everything? The variable mystring defined in the application principal (main () function) cannot be accessed in the Write () function.

The reason is that the variable is scoped, and in this scope, the variable is valid. This scope includes code blocks that define variables and blocks of code that are directly nested within them. The blocks of code in a function are different from the code blocks that call them. In write (), no mystring is defined, and the mystring defined in main () is out of scope-it can only be used in main ().

In fact, in write () there can be a completely independent variable mystring, the old code, as follows:

classProgram {Static voidWrite () {stringMyString ="String defined in Write ()"; Console.WriteLine ("Now in Write ()"); Console.WriteLine ("myString = {0}", myString); }     Static voidMain (string[] args) {         stringMyString ="String defined in Main ()";         Write (); Console.WriteLine ("\nnow in Main ()"); Console.WriteLine ("myString = {0}", myString);     Console.readkey (); } }

You can see the results after running.

This code performs the following actions:
? Main () defines and initializes the string variable mystring.
? Main () transmits control to the WRI.
? Write () defines and initializes the string variable mystring, which is completely different from the mystring variable defined in main ().
? Write () outputs a string to the console that contains the value of the mystring defined in write ().
? Write () transfers the control back to main () only.
? Main () outputs a string to the console that contains the value of the mystring defined in main ().

A variable whose scope overrides a function in this way is called a local variable. There is also a global variable whose scope can override multiple functions. Modify the code as follows:

classProgram {Static stringmyString; Static voidWrite () {stringMyString ="String defined in Write ()"; Console.WriteLine ("Now in Write ()"); Console.WriteLine ("Local myString = {0}", myString); Console.WriteLine ("Global myString = {0}", program.mystring); }     Static voidMain (string[] args) {         stringMyString ="String defined in Main ()"; Program.mystring="Global String";         Write (); Console.WriteLine ("\nnow in Main ()"); Console.WriteLine ("Local myString = {0}", myString); Console.WriteLine ("Global myString = {0}", program.mystring);     Console.readkey (); } } 

Another variable, mystring, is added here, which further deepens the hierarchy of names in the code. This variable is defined as follows:

Static string myString;

Note that the static keyword is also required here. In this type of console application, you must use the static or const keyword to define this form of global variables. If you want to modify the value of a global variable, you need to use static because const prohibits modifying the value of the variable.

In order to differentiate between this variable and the local variable with the same name as the main () and write (), the variable name must be categorized with a fully qualified name. This is called the global variable program.mystring. Note that this is required when the global variable has the same name as the local variable. If you do not have a local myString variable, you can use myString to represent a global variable without using program.mystring. If the local variable has the same name as the global variable, the global variable is masked.

Whether to use global variables depends on the position of the function. The problem with using global variables is that they are usually not suitable for "general purpose" functions--these functions can handle any data we provide, not just the data in a particular global variable.

6.2.1 scope of variables in other structures

The scope of a variable contains the code blocks that define them and the code blocks that are directly nested within them. This can also be applied to other blocks of code, such as code blocks for branching and looping structures. Consider the following code:

intfor0; i++) {     string"" + convert.tostring (i);     Console.WriteLine ("{0}", text);} Console.WriteLine ("lastText output in loop: {0}"

The string variable text is a local variable for the For loop, and this code cannot be compiled because Console.WriteLine () called Outside the loop attempts to use the variable text, which is beyond the scope of the loop. Modify the code as follows:

 int   I;  string   text;  for  (i = 0 ; i < 10 ; I++ =  line   " + convert.tostring (i); Console.WriteLine (  {0}   "   last text output in Loop: {0}   ", text); 

This code also fails, , and text is initialized in the for loop. The value assigned to text is lost when the loop block exits. However, you can also make the following modifications:

 int   I;  string  text =   for  (i = 0 ; i < 10 ; I++ =  line   " + convert.tostring (i); Console.WriteLine (  {0}   "   last text output in Loop: {0}   ", text); 

Declaring only one simple variable type does not cause any other changes. This value takes up a block of memory space only after assigning a value to the variable. If the behavior that occupies memory space occurs in a loop, the value is actually defined as a local value that is outside the scope of the loop.

Even if the variable itself is not localized to the loop, the value contained in the loop is also localized to the loop. However, assigning a value outside the loop ensures that the value is a local value of the body code and that it is still in its scope inside the loop. This means that the variable does not go out of scope before exiting the body code block, so it can access its value outside of the loop.

The last issue to note is that "best practices" should be used. In general, it is a good idea to use them in a block of code after declaring and initializing all of the variables. One exception is to declare a loop variable as part of a loop block, for example:

 for (int0; i++) {     ...}

(original) C # learning note 06--function 02--variable scope 01--other structures

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.