On the difference between Const and readonly in C #

Source: Internet
Author: User
Tags constant constructor

C # introduces the ReadOnly modifier to represent a read-only field, and a const to represent invariant constants. What is the difference between the name of a read-only domain and the immutable constants cannot be modified?

The concept of const is a variable that contains a value that cannot be modified.

A constant expression is an expression that can be fully evaluated at compile time. Therefore, you cannot initialize constants by extracting values from a variable.

If the const int a = B+1;B is a variable, it is obvious that the result cannot be computed at compile time, so constants cannot be initialized with variables.

ReadOnly allows you to set a field to a constant, but you can perform some operations to determine its initial value.

Because ReadOnly is performed at the time of calculation, it can be initialized with certain variables, of course.

ReadOnly are instance members, so different instances can have different constant values, which makes readonly more flexible.

The ReadOnly keyword differs from the const keyword.

1. The const field can be initialized only in the declaration of that field.

The readonly field can be initialized in a declaration or constructor. Therefore, depending on the constructor used, the ReadOnly field may have different values.

2. The const field is a compile-time constant, and the ReadOnly field can be used to run the constant number.

3. The const default is static, and readonly must display the declaration if it is set to static.

4.const for constants of reference types, the possible values can only be string and null.

ReadOnly can be of any type

Summarize

Const can be initialized with constants only in the early stages. For each compiled result, the const value is fixed and the value of the readonly can be determined at runtime.

The above mentioned is the entire content of this article, I hope you can enjoy.

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.