There are two type of constant in C#
- const – Compile time constant.
- readonly – Runtime constant.
const (Compile time constant) are bit faster but less flexible where readonly (runtime constant) are bit slower in comparison with const but more flexible. (If you change value of const in your class then every client code which using the reference of that class.)
If you define any const and use in you code it actually it replace with the value to const instead of holding the reference of const. Which makes const bit faster in comparison with readonly. But it also make less flexible.
- const can only be primitive type (numeric and string) because it has to replace the value to const where it used in code that’s why and any runtime evaluation is not allowed.
- If you change the value to const in you code then every assemblies which using that const must be recompile otherwise changes would not be reflect.
readonly can only be initialize while declaration or in constructor but not after that while const can declare in method as well. That make readonly flexible enough to create different constant for each instance of class which is not possible with const. Another flexibility with readonly is it can be any type.
If readonly is refrence type then reference is immutable but actual object is not; means we can change the reference but we can change the same object (like changing the data for its properties or data member).
I am not a native English speaker nor well trained. Please feel free to comment on the post for any mistake related to spellings, grammar etc, so that I can improve it based upon your suggestion.
Like this post → follow me on twitter @imaheshsingh
Stumble It! Share on Facebook! Tweet it!