Summary of ReadOnly and const usages in C #

Source: Internet
Author: User

Summarize the differences between constants and read-only fields:

Origin:

The author is also looking at the Oulich version of the ". Net Programmer Interview Book", only to find that they have long been confused in the case of both, mixed with such a long time. Indeed, Const is much like ReadOnly, where variables are declared read-only and cannot be rewritten after the variables are initialized. So, what is the difference between the two modifiers, const and readonly? In fact, this involves two different constant types in the C # language: Static constants (Compile-time constants) and dynamic constants (runtime constants). The two have different characteristics, and the wrong use will not only lose efficiency, but also cause errors.

First, explain what the static constants are and what the dynamic constants are. A static constant is a compiler that parses a constant at compile time and replaces the value of the constant with the initialized value. While the value of the dynamic constant is obtained at the moment of operation, it is marked as a read-only constant during compiler compilation, instead of the constant value, so that the dynamic constant does not have to be initialized at the time of declaration, but can be deferred to the constructor initialization.

When you have a general understanding of the two concepts above, then you can explain the const and readonly. Const-Modified constants are the first of these, static constants, while ReadOnly is the second, dynamic constant. The difference can be explained by the characteristics of static constants and dynamic constants:

1) const-modified constants must be initialized at the time of Declaration; readonly-Modified constants can be deferred to constructor initialization

2) const-modified constants are parsed during compilation, that is, constant values are replaced with initialized values; readonly-Modified constants are deferred until run time

In addition, const constants can be declared either in a class or within a function body, but static ReadOnly constants can only be declared in a class.

A. Difference in value:

Constant (CONST): is a value that is known and cannot be modified. Const is static and cannot be modified with static. Use class to access

Read-only Field (READONLY): Only modified in constructors, the value of a read-only field cannot be determined at compile time, but at run time.

ReadOnly can be modified with static or not.

Two. Assignment method differences:

Constant (CONST): A value can only be assigned at declaration time, and the value of the constant is determined at compile time and cannot be changed in the program.

Read-only Field (readonly): Read-only fields can be assigned values at declaration time or within constructors. A read-only field can be a static field (a class has only one value), or it can be an instance field (each instance has its own value).

const defines static constants that are often assigned when an object is initialized. A const-modified constant must be assigned at the same time as the declaration, and it cannot be changed later. It is a compile constant. cannot be initialized with new.

Const-Modified constants are static variables and cannot be obtained for objects

Readonly is a read-only variable. It is a run-time variable. You can change its value in the class constructor. Cannot act on local variables.

(therefore variables modified by ReadOnly can only be assigned during initialization-declaration initialization or constructor initialization-no other place can be assigned to read-only domains)

ReadOnly is only used to modify Class field (fields)

        public const int x = ten;        Public Const String A = "s";        Public Const User CA = null;        Public readonly User Canew = new user ();        Public readonly User Animal;        protected static readonly DateTime StartTime;

  

Both readonly and const are used to identify constants.

    • The const can be used to modify the field of class or a local variable (local variable), while ReadOnly is used only to modify the field of class.
    • The value of a const constant must be clear and constant at compile time, whereas the ReadOnly constant is a bit different, that is, its value can be compiled at run time, and of course it has to obey the constraint as a constant, that is, the value must be constant.
    • The const constant must be assigned at the same time as the Declaration, and ensure that the value is deterministic and constant at compile time, whereas the ReadOnly constant can optionally be given a compile-time determined and constant value at the same time as the declaration, or the initialization of its value is given to the instance constructor (instant constructor) complete. For example: Public readonly string m_now = DateTime.Now.ToString (), M_now will change as the runtime situation changes.
    • A const constant belongs to the class level, not to the instance object level (Instant object), and it cannot be used in conjunction with static. The value of the constant is shared by all instance objects of the entire class (see the remark area later in detail).
    • The readonly constant can be either a class level or an instance object level, depending on its declaration and how the initialization work is implemented. ReadOnly can be used in conjunction with static to specify that the constant belongs to the class level, and the initialization work is referred to the static constructor (static constructor) (see the following remark area for a description of how to declare a ReadOnly constant as a class level or an instance object level).
    • A type that can be declared as constant by a const modifier must be the following primitive type (primitive type): Sbyte,byte, Short,ushort, Int,uint,long,ulong, Char,float, double,float , Bool,decimal, String.
    • Object, array, and struct (struct) cannot be declared as const constants.
    • In general, a reference type cannot be declared as a const constant, with one exception: string. The value of the const constant of the reference type can have two cases, string or null. In fact, string is a reference type, but. NET deals with it especially, which is called string constancy (immutable), which makes the value of string read-only.

Summary of ReadOnly and const usages in 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.