C # variable definition and scope Summary

Source: Internet
Author: User

1.1 variable Declaration

The declaration of variables in C # is illustrated by examples. For example, int I; this statement declares an int (integer) variable I. Another example is string str; which declares a string (string type)

Variable str.

1.2 variable Initialization

C # The Compiler requires that each variable be used after the initial value.

Note the following when initializing C # VARIABLES,

A. variables are fields in A class or structure. If no Explicit initialization is performed, the initial value of these variables is 0 by default. For example, the following code:

using System;
namespace gosoa.com
{
  class MyFirstClass
  {
    static int y;
    static void Main()
    {      
      Console.WriteLine(y);
    }
  }
}

We declare a variable y in the class, and then output the variable. After compilation and running, we will see that the output result is 0.

B. the variables in the method must be explicitly initialized. Otherwise, errors may occur when the variable is used. The following code: an error is reported during compilation. We need to explicitly initialize int y;

. For example, if we initialize the value of y to 10, that is, int y = 10, it will be compiled.

using System;
namespace gosoa.com
{
  class MyFirstClass
  {
    static void Main()
    {
      int y;
      Console.WriteLine(y);
    }
  }
}

 

There are two ways to define constants in C #: compile-time constant and runtime constant ). The former is defined by "const", and the latter is defined by "readonly.
For a static constant (compile-time constant), the writing method is as follows:
Public const int max_value = 10;
Why is it a static constant, because the above statement can be understood as follows (Note: The following statements are incorrect and may cause compilation errors, which is just for convenience ).
Public static const int max_value = 10;
Constants defined by const are the same for all class objects. Therefore, you need to access the constants defined by const as you access static members, however, access by object members may cause a mutation error. In addition, access to static constants replaces constants with their values during compilation. For example:
Int nvalue = max_value;
After compilation, this sentence is the same as the intermediate language code generated in the following sentence.
Int nvalue = 10;
However, there are many restrictions on the type when using const to define constants. First, this type must belong to the value type, and initialization of this type cannot be completed through new. Therefore, some value type constants defined by struct cannot be defined by const.
Compared with const, it is more flexible to use readonly to define constants. The writing method is as follows:
Public readonly int MAX_VALUE = 10;
Why is it a dynamic variable, because the system allocates space for constants defined by readonly, that is, it has independent space like other members of the class. In addition to defining constant values, the constants defined by readonly can be set in the constructor of the class. Since the constants defined by readonly are equivalent to the members of the class, the type restriction for defining constants using const disappears when readonly is used for definition, you can use readonly to define constants of any type.
In summary, the differences between the two are as follows.
Static constant (Compile-time constant) Dynamic constant (Runtime constant)
Definition You must set the constant value when declaring. You do not need to set constant values when declaring them. You can set them in the constructor of the class.
Type restrictions First, the type must belong to the value type range, and its value cannot be set through new. No limit. You can use it to define constants of any type.
For class objects For all class objects, the constant value is the same. For different objects of a class, the constant value can be different.
Memory consumption None. To allocate memory, save the constant entity.
Summary The performance is slightly higher and there is no memory overhead, but there are many restrictions and they are not flexible. Flexible and convenient, but with low performance and memory overhead.

When defining constants, whether it is defined by const or readonly is used. In the past, I tried to use const to define constants in pursuit of performance. However, this book mentions a potential bug about using const. When a program uses a static constant of a class in the DLL class library, if the value of the static constant is modified in the class library, other interfaces do not change. Generally, the new class library can be called directly by executing the program without re-compiling. However, in this case, potential bugs may occur. This is because the static constant is replaced with its value during compilation, so is the replacement of the program at the call end.
For example, a static constant is defined in the class library, as follows:
Public const int MAX_VALUE = 10;
For the code that calls this static constant in the program, in the compiled intermediate language code, it is replaced with 10, that is, the place where the static constant is used is changed to 10.
When the static variables of the class library change, for example:
Public const int MAX_VALUE = 15;
Therefore, the calling end program can be run without re-Compiling. However, the intermediate language code of the program corresponds to the value of the static variable 10, rather than 15 in the new class library. Therefore, such inconsistencies may cause potential bugs. The method to solve this problem is to re-compile the calling program after updating the class library to generate a new intermediate language code.
For the above potential bugs that exist when the const defines constants, readonly does not occur when defining constants. Because the constants defined by readonly are similar to the members of the class, you need to access them according to the specific constant address during access to avoid such bugs.
We recommend that you replace the const with readonly to define constants.

 

The scope of a variable refers to the code area where the variable can be used. In general, it is determined that the scope has the following rules.

A. As long as the class to which the variable belongs is in A specific scope, its field (also called member variable) is also in this scope.

B. Local variables exist in the scope before the block statement or method braces that declare the variable end.

C. The variables declared in the for and while loops only exist in this loop. Body .

When using variables, naming conflicts may occur. First, let's look at the scope conflict of local variables. Example code:

using System;
namespace gosoa.com
{
  class MyFirstClass
  {
    static void Main()
    {      
      for(int i=0;i<10;i++)
      {
        Console.WriteLine(i);
      }
      for(int i=0;i<20;i++)
      {
        Console.WriteLine(i);
      }
    }
  }
}

I is used in both loops, but both can be normally output, because each I scope is in the corresponding two loops.

Let's look at the following code:

using System;
namespace gosoa.com
{
  class MyFirstClass
  {
    static void Main()
    {
int j=5;
      for(int i=0;i<10;i++)
      {
        int j=20;
        Console.WriteLine(i+j);
      }
    }
  }
}

This code compilation will cause errors, because the first j is in the scope of the entire Main () method, which is also effective in the loop body. Therefore, an error is reported when a j with the same name is defined in the loop body.

 

Let's look at the following sample code,

using System;
namespace gosoa.com
{
  class MyFirstClass
  {
    int j=30;
    static void Main()
    {
      int j=20;
      int i=5;
      Console.WriteLine(i+j);
    }
  }
}

In this Code, the scope of the first j is the entire class, that is, the class field. The Declaration of the Second j replaces the first j, so the program will output 25.

1.4 Constants

When declaring a variable, you can add the const keyword before the variable to specify the variable as a constant.

Pay attention to the following points,

A constant must be initialized at the time of declaration, and it cannot be changed after being assigned A value.

Constant B is always static and does not need to add a static keyword when declaring a constant.

 

 

1.3 Scope of Variables

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.