Difference between const and readonly in C #

Source: Internet
Author: User

C # introduces the readonly modifier to represent the read-only domain, and const to represent constant. As the name implies, the read-only domain cannot be written, and constant cannot be modified. What is the difference between the two? A read-only domain can only be assigned a value during initialization -- declaring initialization or constructor initialization -- and cannot be assigned to a read-only domain elsewhere. Otherwise, the compiler reports an error. The read-only domain can be an instance domain or a static domain. The type of the read-only domain can be any type of the C # language. However, the const-modified constant must be assigned a value at the same time as it is declared, and the compiler is required to calculate this definite value during compilation. The constant modified by const is a static variable and cannot be obtained by the object. The type of the value modified by const is also limited. It can only be one of the following types (or can be converted to the following types): sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, enum type, or reference type. It is worth noting that the reference type here, except for the string type, all types out of the null value cannot be calculated by the compiler during the compilation period, therefore, the reference type declared as const can only be string or other reference types whose values are null. Obviously, when we declare a null constant, we have lost the meaning of the Declaration-this can be said to be the embarrassment of C # design!

That is to say, when we need a const constant, but its type limits it to be unable to calculate a definite value during compilation, we can solve this problem by interpreting the voice as static readonly. However, there is a slight difference between the two. See the following two different files:

// File1.cs
// Csc/t: library file1.cs
Using System;
Namespace MyNamespace1
{
Public class MyClass1
{
Public static readonly int myField = 10;
}
}


// File2.cs
// Csc/r: file1.dll file2.cs
Using System;
Namespace MyNamespace2
{
Public class MyClass1
{
Public static void Main ()
{
Console. WriteLine (MyNamespace1.MyClass1. myField );
}
}
}

Our two classes belong to two files, file1.cs and file2.cs, and are compiled separately. When the field myField in the file file1.cs is declared as static readonly, if we change the value of myField to 20 due to some need, we only need to re-compile the file file1.cs to file1.dll, we will get 20 when executing file2.exe. However, if we change static readonly to const and then change the initialization value of myField, we must re-compile all files referenced in file1.dll; otherwise, we will reference MyNamespace1.MyClass1. myField will not change as we wish. This requires special attention in the Process of Large system development. In fact, if we can understand that the constant modified by const is calculated at the time of compilation and replaced by every place that references the constant, the readonly value is determined at runtime. It is only after initialization that we don't want its value to change. We can understand the painstaking efforts of C # designers, we can thoroughly grasp the const and readonly actions!

---------------------

Features:

Both readonly and const are used to identify the constant [1].
Const can be used to modify the field of the class or a local variable (local variable); While readonly is only used to modify the field of the class.
The value of the const constant must be clear and constant during compilation, but the readonly constant is a little different, that is, its value can be compiled at runtime. Of course, it must also comply with the constraint as a constant, that is, the value must be constant.
A const constant must be assigned a value while being declared, and the value must be fixed and constant during compilation; the readonly constant can choose to assign a fixed value to it during compilation at the same time as needed, or assign the initialization work of its value to the instance constructor) complete. For example, public readonly string m_Now = DateTime. Now. ToString ();, m_Now changes with the actual situation during running.
Const constants belong to the class level rather than the instant object level, and cannot be used together with static, the value of this constant will be shared by all instance objects of the entire class (For details, refer to the Remark area later ).
The readonly constant can be at the class level or the Instance Object level, depending on its declaration and how the initialization is implemented. Readonly can be used in combination with static to specify that the constant belongs to the class level and submit the initialization work to the static constructor) complete (for details about how to declare a readonly constant as a class or instance object level, see the Remark area later ).
The types declared as Constants by const must be the following primitive types (primitive type): sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, float, bool, decimal, string.
Objects, arrays, and structures cannot be declared as const constants.
Generally, the reference type cannot be declared as a const constant, but there is an exception: string. The value of the const constant of the reference type can be string or null. In fact, although the string type is a reference type,. NET has special processing on it. This kind of processing is called the immutable character string, so that the string value has the read-only feature. For the constant character string content, refer to Microsoft. NET Framework programming (revision).


Examples:

Using System;

Public class Order
{
Public Order ()
{
Guid guid = Guid. NewGuid ();
ID = guid. ToString ("D ");
}

// For each order, the order number is a constant determined in real time.
Public readonly string ID;

Public override string ToString ()
{
Return "Order ID:" + ID;
}
}
Explaintion:

If used in combination with the database, ID field is usually associated with the primary key of a table, such as the OrderID of the Orders table.
The primary keys of a database generally adopt the following three methods:
Auto increment value. You can set DataColumn. AutoIncrement to true to activate the auto-increment feature.
Unique name. This is to generate a unique serial number using a defined algorithm.
GUID (globally unique identifier ). You can use the System. Guid structure to generate a GUID, as shown in the preceding example.
Using System;

Class Customer
{
Public Customer (string name, int kind)
{
M_Name = name;
M_Kind = kind;
}

Public const int NORMAL = 0;
Public const int VIP = 1;
Public const int SUPER_VIP = 2;

Private string m_Name;
Public string Name
{
Get {return m_Name ;}
}

Private readonly int m_Kind;
Public int Kind
{
Get {return m_Kind ;}
}

Public override string ToString ()
{
If (m_Kind = SUPER_VIP)
Return "Name:" + m_Name + "[SuperVip]";
Else if (m_Kind = VIP)
Return "Name:" + m_Name + "[Vip]";
Else
Return "Name:" + m_Name + "[Normal]";
}
}



Remarks:

In general, if you need to declare constants that are universally recognized and used as a single, such as the circumference rate, golden split ratio, and so on. You can consider using const constants, such as public const double PI = 3.1415926 ;. If you need to declare a constant, but this constant will be determined according to the actual running situation, the readonly constant will be a good choice, such as the Order number Order in the first example above. ID.
In addition, if you want to represent the default value inside the object, and such values are usually constant properties, you can also consider const. More often, when we refactor the source code (using Replace Magic Number with Symbolic Constant), the impact of the Magic Number will be attributed to this feature of const.
If the variables modified by readonly and const belong to the class level or the Instance Object level, let's take a look at the following code:

When using Visual C # To insert fields related to Constant Using intelliisence in Main (), we found that ReadonlyInt and InstantReadonlyInt must specify the instance object of Constant.

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.