What is the difference between const and readonly?

Asked

Viewed 2,636 times

25

Read-only constants and fields cannot be modified, as can be seen in the documentation:

const
Constant fields and locations are not variable and cannot be modified.

readonly
When a field declaration includes a readonly modifier, this cannot be amended except as part of the declaration thereof or the construction method of the class belonging.

What are the differences between const and readonly and when to use each?

1 answer

29


const is static and is solved at compile time. That is, what will be put in the code that consumes the constant is the value established in it. If by chance it changes its value, it has to compile everything that consumed it to have the new value. In addition the value has to be constant as well, that is, it has to be able to be completely solved during the compilation. So you can’t use it for much.

A good example is PI.

A bad example for its use is MaxThreads. One day you may want to change and may have problems. In this case it is best to use:

public static readonly int MaxTreads = 4;

I put in the Github for future reference.

readonly can be applied to static or instance fields (there is proposal to have locally). It is not quite a constant, just indicates that after initializing its value can no longer be changed. It is immutable, but not constant, even though he’s usually considered that way. The values used in it can be solved at runtime because its initialization occurs only at that moment, either at the time you need to use static data or at the time of creating an instance depending on the context it is declared.

As the data is initialized at runtime, even if its value can be solved at compile time is not done, so the consumer code of these "constants" are sure that they will always take the current value of the code that created it.

If you need to initialize at runtime you have no option, you can only use readonly. If you need the "constant" to be instance, you should also use readonly.

The basic rule when you choose is that you need a piece of data that you can change in the future, use readonly. If it is universally constant - it will never change - you can use const.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.