What is the difference between const and readonly?

21

Constants and read-only fields can not be modified, as can be seen in the documentation:

  

const
  Fields and constant places are not variables and can not be modified .

  

readonly
  When a field declaration includes a readonly modifier, this can not be changed except as part of the declaration of the field or the constructor method of the class belonging to.

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

    
asked by vnbrs 08.09.2016 в 17:17
source

1 answer

20

const is static and is resolved at compile time. That is, what will be placed in the code that consumes the constant is the value established in it. If by chance you change your value, you have to compile everything you have consumed to have the new value. In addition, the value must be constant as well, that is, it must be able to be completely resolved during compilation. So you can not use it for much.

A good example is PI .

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

public static readonly int MaxTreads = 4;

readonly can be applied to static or instance fields. It is not quite a constant, it just indicates that after initialized its value can no longer be changed. It is immutable , but not constant, although usually it ends up being considered this way. The values used in it can be solved at runtime because their initialization occurs only at this time, either at the time they need to use the static data or at the moment of creating an instance depending on the context it is declared. Since the data is initialized at runtime, even if its value can be solved at compile time, it is not done, so the consumer code of these "constants" are sure to always take the current value of the code that the created.

If you need to boot 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 to choose is that if you need a data that can change in the future, use readonly . If it is universally constant - it will never change - you can use const .

answered by 08.09.2016 / 17:26
source