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.