What I understand is readonly and const, readonlyconst

Source: Internet
Author: User

What I understand is readonly and const, readonlyconst

Recently, I want to give a few lectures to new members of the school's software team, so I learned a lot of hard-to-learn and ambiguous knowledge points again.

MSDN explains this as follows:

The readonly keyword is different from the const keyword. 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. In addition, the const field is the number of compiling times, while the readonly field can be used for running times.

What is the compile-time constant and the runtime constant. I want to do the following experiment. You will understand readonly and const better.

Create a new class library outside the project. A TestClass class in the class library defines a const field and a readonly field.

Public const int paramones = 100;

Public static readonly int ParamTwo = 100;

 

Call and output two values in the console. The expected effect is of course 100,100;

 

The following will help you understand the difference between const and readonly.

 

Modify ParamOne = 50; ParamTwo = 50;

 

Do not regenerate the entire project. Only the class library is regenerated. Find the dll file in the bin directory and copy it to the bin directory in the console (the purpose is not to re-compile the console project)

 

Double-click the exe file in the console. What will happen next?

 

The output values are 100 and 50;

 

That is to say, the value of const has not changed, but the value of readonly has changed.

 

Why?

 

The value of const is saved to the metadata and directly embedded in the Code. The value of readonly is a value assigned at runtime.

 

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.