Compare readonly and const in C)

Source: Internet
Author: User
Document directory
  • Feedback

C # has two constant types: readonly (runtime constant) and const (compilation constant ), this article compares the two types of features and describes their application scenarios.

Working Principle
Readonly is the runtime constant. It is assigned a value when the program is running. It cannot be changed after the value is assigned. Therefore, some people call it a read-only variable.
Const is the compile-time constant. During program compilation, constant values are parsed and all constant references are replaced with corresponding values.
The following two constants are declared: public static readonly int A = 2; // A is the runtime constant.
Public const int B = 3; // B indicates the compile time.

The following expression:

Int c = A + B;

After compilation, it is equivalent to the following form:

Int c = a + 3;

As you can see, const constant B is replaced with the word surface volume 3, while readonly constant A remains the reference mode.

Declaration and initialization
The readonly constant can only be declared as a class field. It supports instance type or static type. It can be initialized at the same time of Declaration or in the constructor. After initialization, it cannot be changed.
In addition to being declared as a class field, const constants can also be declared as local constants in methods. The default value is static type (without static modification; otherwise, compilation errors will occur ), however, initialization must be completed at the same time as the declaration.


Supported Data Types

Const constants are replaced with literal values during compilation, which limits their value types. Const constants can only be assigned numbers (integers, floating-point numbers), strings, and enumeration types. The following code cannot be compiled: Public const datetime d = datetime. minvalue;

Change to readonly to compile normally:

Public readonly datetime d = datetime. minvalue;

 


Maintainability

Readonly works in reference mode. After a constant is updated, all the places that reference this constant can get the updated value.
Const is a little more complex, especially cross-assembly call: public class class1
{
Public static readonly int A = 2; // A indicates the running time.
Public const int B = 3; // B indicates the compile time.
}

Public class class2
{
Public static int c = class1.a + class1. B; // The value of variable C is the sum of A and B.
}

Console. writeline (class2.c); // output "5"

 

Assume that class1 and class2 are in two different sets, and now change the constant value in class1:

Public class class1
{
Public static readonly int A = 4; // A indicates the running time.
Public const int B = 5; // B indicates the compile time.
}

Compile and deploy class1 (Note: class2 is not re-compiled at this time), and check the value of variable C again:

Console. writeline (class2.c); // output "7"

The result may be a little unexpected. Let's take a closer look at the value assignment expression of variable C:

Public static int c = class1.a + class1. B;

After compilation, it is equivalent to the following form:

Public static int c = class1.a + 3;

Therefore, no matter how the value of constant B changes, it will not affect the final result. Although re-compiling class2 can solve this problem, at least we can see the possible maintenance problems caused by const.

 

Performance Comparison
Const is directly involved in the operation in literal form, and the performance is slightly higher than readonly, but for general applications, this performance difference can be said to be minimal.

Applicable scenarios
In the following two cases:
A. The value remains unchanged permanently (such as the circumference rate, the number of hours in a day, and the Earth's radius)
B. Strict Program Performance Requirements
You can use the const constant. In other cases, the readonly constant should be used first.

Tag: C #,. net

Feedback #1 floor reply reference

By C # fans [unregistered users] just to learn. Thank you. # Reply to reference on the second floor

By Niu [unregistered users] talked about some basic knowledge. # View the reply reference on the third floor

By stevenju how do I say in the garden that readonly is a read-only variable, or a definition constant? What is it?
Class1 and class2 are located in two different sets. Now, after changing the constant value in class1, how is the output result 7 ?? # View the reply reference on the 4th floor

2008-05-27 by Shui yanmu @ steenju
I think it would be better to call "Read-Only variables". In fact, all of them mean one.
Strictly speaking, a constant must be assigned a value during declaration and cannot be assigned again, but readonly is not. It can be assigned again in the constructor, and the value of a constant is determined during compilation. # Reply to reference on the 5th floor

By Zhifeng Yu [unregistered user] const is a variable that contains unchangeable values.
Constant expressions are fully computed during compilation. Therefore, constants cannot be initialized by extracting values from a variable.
If const int A = B + 1; B is a variable, it is obvious that the result cannot be calculated during compilation, so constants cannot be initialized using variables.

Readonly allows a field to be set as a constant, but some operations can be performed to determine its initial value.
Because readonly is executed during computing, of course it can be initialized with some variables.
Readonly is an instance Member, so different instances can have different constant values, which makes readonly more flexible.

The readonly keyword is different from the const keyword.

1. the const field can only be initialized in the declaration of this field.
The readonly field can be initialized in the Declaration or constructor. Therefore, the readonly field may have different values based on the constructors used.
2. the const field is the number of compiling times, while the readonly field can be used for running times.
3. const is static by default, and readonly must display the declaration if it is set to static.
4. For constants of the reference type, the possible values of const can only be string and null.
Readonly can be of any type

* You need to pay attention to the following issues:

For a readonly reference type, the value assignment (write) operation is not allowed. The read and write operations on its members are still unrestricted.

Public static readonly class1 my = new class1 ();
...
My. someproperty = 10; // normal
My = new class1 (); // error. The object is read-only.

However, if the class1 in the above example is not a class but a struct, then the following two statements will go wrong.

Static readonly:

In Java, static is executed once when a class is loaded.

C. It is strange that almost every Java book will talk about the static problem. C # often only describes how to use it, but it should be initialized before the main function is called, so static readonly is also running, and can be used to pay the value, such:

Private Static readonly string Path = system. Windows. Forms. application. startuppath + "AAA ";

-- From the LTP. Net Knowledge Base Series

# View the reply reference on the 6th floor

By zmxmiss learning #7 floor reply reference View

By Da Vinci Objective C #
Rule 2: Try to use readonly instead of const
Only readonly has poor performance.
Check the situation. # Check the reference on the 8th floor.

By 81 was well written. In different assemblies, we did not notice the problem of const processing. # View the reply reference on the 9th floor

By Da Vinci @ Stephen
Readonly is a dynamic constant and const is a static constant.
Memory needs to be allocated for constants defined by readonly
4 + 3 = 7 # view the reference on the 10th floor

By Da Vinci @ 81
Therefore, const may cause errors # review references on the 11 th floor

By coderzh very good # reply to reference on the 12th floor to view

By steenju @ Shui yanmu
@ Da Vinci
Thank you very much. Now I understand! # View the reply reference on the 13th floor

2008-05-27 by stevenju @ wind feather
Thank you very much! # View the reply reference on the 14th floor

By OOP well written. # Reply to reference on the 15th floor

By wxc [unregistered users] supplement wind feather:

Const can modify both the members of a class and the local variables in the function body.
Readonly can only modify the members in the class # reply to reference on the 16th floor to view

By anytao is well written.
However, I think it is not comprehensive enough. In fact, static readonly and const are more comparable and can be more specific in the scope of application. For example, readonly cannot modify local variables, while const can...

In addition, the statement "readonly is the number of runtime times, and the value is assigned when the program is running. Once the value is assigned, it cannot be changed." In fact, the value of readonly can be changed, you can make changes within the constructor.

Therefore, we can see more thoroughly from the memory perspective :-)

Thank you for your wonderful message:-) # reply to reference on the 17th floor

By anytao l In addition, for read-only features, I think the set and get accessors of the attribute can be read and written. For encapsulation, have a more elegant code experience and reliability :-) # on the 18 th Floor, [the landlord] Reply to the reference for viewing

By Kenny @ Web @ anytao
Thank you for your suggestion. The content has been supplemented:-) # reply to reference on the 19th floor.

By seeking knowledge without pride at night # reply to reference on the 20th floor

By train-I [unregistered user] said in detail #21 floor reply reference View

Do not mislead the children;

Readonly is definitely not a constant;

This is called a read-only variable ";

It just seems like a constant, a pseudo constant;

C # code

Public class sampleclass
{

Const int c = 25;
Readonly int r = 25;

Public void test ()
{

Console. writeline (C );
Console. writeline (R );
}
}

After compilation

Public class sampleclass
{

Private const int C = 0x19;
Private readonly int r = 0x19;

Public void test ()
{
Console. writeline (0x19 );
Console. writeline (this. R );
}
}

Simply put, "constants" are directly placed in the code during compilation, rather than pointing to a variable.

# Reply to reference on the 22nd floor

By James dai [unregistered user] Static readonly is to get the address,
Const directly obtains the value. It is similar to shallow copy and deep copy # 23rd floor reply reference

By lonely_c # [unregistered users] So many people have learned C #.

Related Article

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.