gotchacsharpCritical
What is the difference between const and readonly in C#?
Viewed 0 times
readonlyconstandbetweenthedifferencewhat
Problem
What is the difference between
When would you use one over the other?
const and readonly in C#? When would you use one over the other?
Solution
Apart from the apparent difference of
There is a subtle difference. Consider a class defined in
So if you are confident that the value of the constant won't change, use a
But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a
Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: Effective C# - Bill Wagner
- having to declare the value at the time of a definition for a
constVSreadonlyvalues can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen.
const's are implicitlystatic. You use aClassName.ConstantNamenotation 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
constvalue, it is like a find-replace. The value 2 is 'baked into' theAssemblyB's IL. This means that if tomorrow I updateI_CONST_VALUEto 20,AssemblyBwould still have 2 till I recompile it.
- in the case of the
readonlyvalue, it is like arefto a memory location. The value is not baked intoAssemblyB's IL. This means that if the memory location is updated,AssemblyBgets the new value without recompilation. So ifI_RO_VALUEis updated to 30, you only need to buildAssemblyAand 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;Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: Effective C# - Bill Wagner
Code Snippets
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;
}
}public const int CM_IN_A_METER = 100;public readonly float PI = 3.14;Context
Stack Overflow Q#55984, score: 1590
Revisions (0)
No revisions yet.