Clause 2: readonly is better than Const)

Source: Internet
Author: User
The C # language has two different constants: A complie-time constant and a runtime constant. The two constants have different behaviors. Incorrect use may lead Program Or an error occurs. The compile time is a little faster than the run time, but it lacks flexibility. Only when the performance is critical and Its Value never changes, we should use the compile-time workload.
In C #, we use the readonly keyword to declare the runtime constant, and the const keyword to declare the compilation constant.

// Compilation frequency:
Public   Const   Int _ Millennium =   2000 ;
// Running frequency:
Public   Static   Readonly   Int _ Thisyear =   2004 ;

The differences between the compile-time and run-time behaviors are their access methods. The results of the compilation from time to timeCodeWill be replaced with the value of this constant.

If (Mydatetime. Year = _ Millennium)

The compiled Il is the same as the compiled Il of the following code:

If (Mydatetime. Year =   2000 )

The value of the runtime constant is calculated at runtime. For code that uses the regular amount of runtime, the compiled Il will maintain reference to the readonly variable (rather than its value.
This difference will impose some restrictions on the use of the two constant types. Compile time can only be used for primitive types (including built-in integer and floating point types), enumeration type, or string type. This is because only these types allow us to specify meaningful constant values in the initializer. (Declare and initialize at the same time ). In the Il Code Compiled using the code of these constants, constants are directly replaced with their literal values (literal ). For example, the following code will not be compiled. In fact, C # does not allow us to use the new operator to initialize a compilation constant, even if the initialized constant type is a value type.

// The following code will not be compiled, but can be changed to readonly:
Private   Const Datetime _ classcreation =   New Datetime ( 2000 , 1 , 1 , 0 , 0 , 0 );

The compilation frequency is limited to numeric values and strings. Read-Only fields are also called constants because once their constructors are executed, they cannot be modified. The difference from the compilation frequency is that the assignment operation of read-only fields occurs at runtime, so they have more flexibility. For example, there are no restrictions on the type of read-only fields. For read-only fields, we can only assign values to them in the constructor or initialization. In the above code, we can declare the datetime structure variable of readonly, but cannot declare the datetime structure variable of Const.
We can declare the readonly instance constant to store different values for each instance of a type. However, the const-modified compilation frequency is defined as a static constant by default.
We know that the most important difference between the runtime constant and the compilation constant is that the runtime constant value occurs at runtime, while the compilation constant value occurs at compilation. In other words, the compiled il code often references the readonly variable rather than its value; when compiling, the compiled il code will directly reference its value, just as we use a constant value directly in the code. Even if we are using a numeric constant and cross-Assembly reference, the same is true: If we reference a constant in assembly B in assembly, after compilation, the constant in Assembly A will be replaced by its value. This difference has a considerable impact on code maintainability.
The Parsing Method of the compilation and running often affects the runtime compatibility. Suppose we have defined a const field and a readonly field in a set named infrastructure:

Public   Class Usefulvalues
{
Public   Static   Readonly   Int Startvalue =   5 ;
Public   Const   Int Endvalue =   10 ;
}

In another assembly application, we reference these values:

For ( Int I = Usefulvalues. startvalue; I < Usefulvalues. endvalue; I ++ )
{
Console. writeline ("Value is {0}", I );
}

If we run the above Code, we will get the following output:
Value is 5
Value is 6
......
Value is 9
Assume that over time, we have released a new version of the Infrastructure assembly:

Public   Class Usefulvalues
{
Public   Static   Readonly   Int Startvalue =   105 ;
Public   Const   Int Endvalue =   120 ;
}

we distributed the new version of the Infrastructure assembly, but did not re-compile the application assembly. We expect the following output:
value is 105
value is 106
......
value is 109
but we didn't actually get any output. Because the loop statement uses 105 as its starting value and 10 as its ending condition. The root cause is that the C # compiler replaces endvalue with its constant value 10 when compiling the application Assembly for the first time. For startvalue, because it is declared as readonly, its parsing occurs at runtime. Therefore, the application assembly can still use the new startvale value without being re-compiled. To change the behavior of all customer code that uses readonly constants, simply install a new version of the Infrastructure assembly. "Changing the value of a runtime constant" should be treated as a change to the type interface. The consequence is that we must recompile all code that references this constant.
the only advantage of using const over using readonly is performance: using a known constant value code is more efficient than accessing the readonly value code. However, the efficiency improvement in this process is very small. We should make a trade-off with the lost flexibility. Before giving up flexibility, you must evaluate the performance difference between the two.
to sum up, you should consider using const only when the value of the variable must be available during compilation in some cases. For example, parameters of the attribute class, enumeration definition, and some values that do not change with the component version. Otherwise, the readonly constant should be selected first in any other case to obtain its flexibility.

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.