Developer community
0 votes
138 views
What is the difference between const and readonly and do you use one over the other?
asked by Sr Member (1.1k points) 13 27 42 | 138 views

1 Answer

0 votes
Best answer

Apart from the apparent diff of

  • having to declare the value at the time of a definition for a const VS readonly values can be computed dynamically but need to be assigned before the ctor exits.. after that it is frozen.
  • 'const's are implicitly static. You use a ClassName.ConstantName notation to access them.

There is a subtle difference. Consider a class defined in AssemblyA.

public class Const_V_Readonly 
{ 
 
public const int I_CONST_VALUE = 2; 
 
public readonly int I_RO_VALUE; 
 
public Const_V_Readonly() 
 
{ 
     I_RO_VALUE
= 3; 
 
} 
} 
 

AssemblyB references AssemblyA and uses these values in code. When this is compiled,

  • in the case of the const value, it is like a find-replace, the value 2 is 'baked into' the AssemblyB's IL. This means that tomorrow if I update I_CONST_VALUE to 20 in the future. Assembly B would still have 2 till I recompile it.
  • in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, Assembly B gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled.

So if you are confident that the value of the constant won't change use a const.

public const int CM_IN_A_METER = 100; 

But if you have a constant that may change (e.g. w.r.t. precision).. or when in doubt, use a readonly.

public readonly float PI = 3.14; 
answered by Sr Member (1.9k points) 1 2 6

Related questions

0 votes
1 answer
asked by shivani Sr Member (1.1k points) 13 27 42 | 388 views
0 votes
1 answer
0 votes
1 answer
asked by john Guru (27.1k points) 31 47 92 | 64 views
0 votes
1 answer
asked by arnav Sr Member (1.3k points) 9 21 28 | 82 views
0 votes
1 answer
asked by sara Guru (24.6k points) 29 51 77 | 39 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users