Difference between const and static readonly

Source: Internet
Author: User
Const
Modify the declaration of a field or local variable. It specifies that the value of a field or local variable is a constant and cannot be modified. The value of a constant must be determined during compilation. After compilation, CLR stores the value of a constant in the negative data of assembly. If the variable is const, It is implicitly static. Therefore, you only need to declare the variable as const when declaring a constant, rather than using static when declaring a constant.
When Code When a constant is referenced, CLR searches for the symbol in the metadata and embeds the extracted constant value into Il. Therefore, the constant does not have an address and the allocated memory, and variables cannot be passed through reference.

Readonly
The modifier used on the field indicates that the field is read-only. When a field is declared as readonly, there are only two ways to assign values to it, that is, it appears as part of the Declaration, or in the same class of constructor.
For instance fields, in the instance constructor that contains the field declaration; or for static fields, in the static constructor of the class containing the field declaration. It is also valid only when the readonly field is passed as the out or ref parameter in these contexts.

Static
Declarations belong to types rather than static members of specific objects. They can be used for classes, fields, methods, attributes, operators, events, and constructors,But it cannot be used for indexers or destructor.Or a type other than the class.
Although the instance of the class contains a separate copy of all instance fields of the class, each static field has only one copy.
A static member cannot be referenced by an instance of the class, but can be referenced by a type name.
If you applyStaticKeyword, all the members of this class must be static
Classes (including static classes) can have static constructors.InProgramCall a static constructor at a certain time between the start and the instantiation class

Const and readonly
Const
1. constants parsed during compilation
2. Initialization must be performed on the Declaration.
3. It can be used to modify members of a class or local variables in a function.
Readonly
1. constants parsed during running,
2. It can be initialized at Declaration or in the constructor. Therefore, the readonly field may have different values based on the constructor used.
3. It can only be used to modify members in a class.

Const and static readonly
They all represent static constants and cannot be changed after being assigned values.

We all know that const and static readonly are indeed very similar: access by class name rather than Object Name, read-only in the program, and so on. In most cases, they can be mixed.
The essential difference between the two is that the const value is determined during compilation, so it can only be specified through a constant expression during declaration. Static readonly calculates its value during running, so it can be assigned a value through a static constructor.
After understanding the essential difference, we can easily see whether static readonly and const can be exchanged in the following statements:
1. Static readonly myclass myins = new myclass ();
2. Static readonly myclass myins = NULL;
3. Static readonly A = B * 20;
Static readonly B = 10;
4. Static readonly int [] constintarray = new int [] {1, 2, 3 };
5. Void somefunction ()
{
Const int A = 10;
...
}

1: cannot be changed to const. The new operator needs to execute the constructor, so it cannot be determined during compilation
2: can be changed to const. We can also see that constants of the reference type (except strings) can only be null.
3: It can be changed to const. We can clearly say that a equals 200 during the compilation process.
4: cannot be changed to const. The principle is the same as that of 1, although it seems that the arrays of 1, 2, and 3 are indeed constants.
5: it cannot be changed to readonly. readonly can only be used to modify the field of the class. It cannot modify local variables or other class members such as property.

Therefore, static readonly can be used for those places that should be essentially constants but cannot be declared using Const. Example in C # specification:

Public class color
{
Public static readonly color black = new color (0, 0, 0 );
Public static readonly color white = new color (255,255,255 );
Public static readonly color red = new color (255, 0, 0 );
Public static readonly color green = new color (0,255, 0 );
Public static readonly color blue = new color (0, 0,255); one of the notes for static readonly is that for a static readonly reference type, values cannot be assigned (written) only if it is limited) operation. The read and write operations on its members are still unrestricted.

Public static readonly myclass myins = new myclass ();
...
Myins. someproperty = 10; // normal
Myins = new myclass (); // error. The object is read-only.

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

 

Private byte red, green, blue;

Public color (byte R, byte g, byte B)
{
Red = R;
Green = g;
Blue = B;
}
}

C # has two different constants: Static constants (compile-time constants) And dynamic State constant (runtime constants) . They have different features. Incorrect use may not only result in loss of efficiency, but also cause errors. In contrast, static constants are slightly faster in terms of speed, but more flexible than dynamic constants.

// Static constants (implicitly static)
Public const int compiletimeconstant = 1;
// Dynamic constant
Public static readonly runtimeconstant = 1;

Static constants are replaced with their corresponding values during compilation,That is to say, the following two statements generate the same il after compilation by the compiler.

// After compilation, the two are translated into the same intermediate language.
Int mynum = compiletimeconstant;
Int mynum = 1;

The value of a dynamic constant is obtained at runtime.Il marks it as a read-only constant instead of a constant value.

Static constants can only be declared as simple data types (built-in int and floating point types), enumerations, or strings. The following program segments cannot be compiled. You cannot use the new keyword to initialize a static constant, even for a value type.

// This is incorrect.
Public const datetime mydatetime = new datetime );
// This is acceptable
Public static readonly datetime mydatetime = new datetime );

Read-only data is also a constant and cannot be modified after the constructor initialization. However, unlike static constants, the value is assigned at run time, which gives more flexibility. Dynamic Constants can be any data type.

The biggest difference between the two is that static constants are converted into corresponding values during compilation, which means that for different assembly, when you change a static constant, you need to re-compile it. Otherwise, the constant value will not change, which may lead to potential problems, but dynamic constants will not.

A constant defined by const (which is implicitly static) needs to access the constant defined by const just like a static member, and a compilation error occurs when accessed by object members. You must set the constant value when declaring.
On the other hand, if you want to declare constants that never change and are unique everywhere, such as the idhook parameter of the hook function setwindowshookex or the version during serialization, you should use static constants. However, there are not many opportunities to use such constants. Generally, we should use dynamic constants with higher flexibility.

Static ConstantsDynamic constant

Memory consumptionNone because constants to be saved consume

InitializationVery few simple types, any type, can be assigned in the class Constructor
Cannot be new, must be in
Assign values at the same time

When to play a roleThe replacement during compilation is equivalent to the data member in the class.

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.