What is the difference between const and readonly in C#?
When would you use one over the other?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Apart from the apparent difference of
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.AssemblyBreferencesAssemblyAand uses these values in code. When this is compiled: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.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.But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a
readonly.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