Readonly
- When a field is declared with readonly, it needs to be initialized either during declaration or in a constructor.
public class Const_V_Readonly
{
public readonly int Readonly_Value;
public Const_V_Readonly()
{
Readonly_Value = 3;
}
}
public class Const_V_Readonly
{
public static readonly int Readonly_Value;
//Access modifiers are not allowed on static constructors
static Const_V_Readonly()
{
Readonly_Value = 3;
}
}
- If consider "Const_V_Readonly" class in AssemblyA , AssemblyB references AssemblyA and uses these values in code. When AssemblyA is compiled, readonly values are 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, AssemblyB gets the new value without recompilation. So if "Readonly_Value" is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled.
- So if you have a constant that may change or when in doubt, use a readonly.
Constants
- A const keyword is used to declare constant fields and constant local.
- The value of the constant field is the same throughout the program or in other words, once the constant field is assigned the value of this field is not be changed.
public class Const_V_Readonly { public const int Constant_Value = 2; }
- The constant field should be initialized on the declaration. (Can not intialize it in a constructor or method)
- If consider "Const_V_Readonly" class in AssemblyA and AssemblyB references AssemblyA and uses these values in code. When AssemblyA is compiled, const value is like a find-replace, the value 2 is 'baked into' the AssemblyB's IL. This means that if we update Constant_Value to 20 in the future. AssemblyB would still have 2 till we recompile it.
- So if you are confident that the value of the constant won't change use a const.
No comments:
Post a Comment