Const, readonly. Do you really understand this? May be interviewed... constreadonly

Source: Internet
Author: User

Const, readonly. Do you really understand this? May be interviewed... constreadonly

 

First of all, it is undeniable that these questions will be frequently asked by the interviewer during the interview, but are your answers satisfying the interviewer? Of course, if you understand these principles, you may not

Afraid. Since the principles are introduced, let's start with MSDN.

I. Several points worth further consideration

1. Let's take a look at what const says on msdn. We will see it. It cannot be modified. This key information is often used during compilation.

 

Q: Why can't the const be modified.

 

A: This is very simple. Many textbooks have mentioned that when the compiler compiles, the constant value will be saved in the metadata of the Assembly. Let's make an example below.

Take a look.

①: Create a project.

1 // ProjectA2 public class TestClass3 {4     public const int CTRIP = int.MaxValue;5 }

Create another MainProject and reference projectA.

 1 using System; 2  3 class Program 4 { 5     static void Main(string[] args) 6     { 7         Console.WriteLine(TestClass.CTRIP); 8  9         Console.Read();10     }11 }

Then we run mainproject.

 

Now that I ran mainproject and referenced Test. dll, we also mentioned that the constant value will be stored in the Assembly metadata during compilation.

Open ildasm.exe and press Ctrl + M.

 

 

Unfortunately, I did not find the Ctrip symbol, int. MaxValue, or the so-called 0x7fffffff, but I found an Assembly.

Some version information metadata, you may be confused at this time, whether the const value is saved in the Assembly? A simple verification

The method is to delete Test. dll from the bin in Mainproject to see what happens.

 

 

At this time, you will find that test. dll has been deleted. Since Demo.exe can still run, it indicates that the const value is actually written into the Assembly.

Go. Otherwise, where does the value come from?

 

②: It should be clear that you should not load Test. dll when running demo.exe, but directly obtain the const value from the Demo Assembly,

Is there a fault, that is, version inconsistency? For example, I have modified the const value and copied the compiled dll to Mainproject.

Run demo.exe directly under the bindirectory. Will the MainProject fail to read the modified const value? Here I change const to int. MinValue.

Next, let's try it.

1 // ProjectA2 public class TestClass3 {4     public const int CTRIP = int.MinValue;5 }

 

Now, seeing the above results further proves the statement just now. The const is actually saved in the Assembly metadata, and the prompt will be sent here.

Here, Enum is essentially a const, so it also has the fault I just mentioned. Here, I think you should be familiar with the const principle.

Let's take a look at Question's problem. What is metadata? "Data describing data" is called metadata, since it is a basic descriptive number.

Therefore, after the definition, it cannot be changed. Is it so easy when this definition is compiled by msdn?

 

Q: Why does const need to be made static instead of an instance?

 

A: In fact, through the analysis of the first Question, many things should be open-minded. Because of the fault, the best method is the value of const.

Never change. In this way, the problem can be avoided. Since it is always the same thing, it is much better to follow the "type" than to follow the "instance", you said

Right? Because static is a small cache, it is not necessary to generate a new one...

 

Q: Can the readonly field be initialized only in ctor?

 

 

A: This question is quite interesting. We know that readonly means read-only fields. We know that general fields have the ability to read and write,

Let's take a look at the compiler.

 

From the compiler, we can see that the initialization of readonly can also be performed during "variable initialization", so the answer to Question is as follows:

It should be no, but is it true? We all know that there is a thing called "syntactic Sugar" which is often provided by the compiler for us.

We can only use ildasm.exe to penetrate the compiler to see what happened.

 

From IL, we can see that it is really the syntactic sugar of the compiler, Which is initialized in the ctor. Therefore, never look at the problem.

 

Note: Stsfld replaces the static field value with the value from the calculation stack.


What is the difference between const and readonly?

Const:
It cannot be static;
The value is specified during compilation;
Values can only be assigned during declaration;
Readonly:
It can be static or non-static;
The value is specified at runtime;
You can assign values during declaration or in constructor.

Different const and readonly examples

The two keywords const and readonly are used in many environments. You didn't say what environment you are using. In most cases, const is used to define constants, that is, the program will not modify the stuff declared by const during runtime (in fact, it cannot be changed, otherwise the compilation will fail ), readonly is the property of some controls such as editing input boxes. It indicates that the text in this box cannot be modified through user operations, however, the program can modify the content of the text at any time in the running state.

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.