C# Hidden Danger #1: The const Keyword
Declaring a constant with the const keyword makes it a compile-time constant. In the generated IL, all references to a compile-time constant will be replaced by its actual value. Now suppose that a compile-time constant is declared in one assembly and referenced in other assemblies. If the definition of the constant ever needs to be changed, all affected assemblies need to be recompiled. Rebuilding and redistributing just the first assembly will not suffice.
Therefore, use the readonly keyword where possible, unless you are absolutely sure that the value will never change. The slight increase in performance afforded by the const keyword is not worth the inflexibility.
4 Responses to “C# Hidden Danger #1: The const Keyword”
1 zeff 11 August 2008 @ 8:15 pm
Meaning that, this ‘readonly’ keyword stored by references and not by value. It is correct?
2 Rizal 11 August 2008 @ 8:18 pm
That is correct.
3 zeff 11 August 2008 @ 8:24 pm
I think the purpose of compile-time constant it to stored as value. Something we just want a primitive value to be set during compile-time constant. By changing the ‘const’ to ‘readonly’ keyword also means storing primitive value as references. It is worth it? Why not set the access-modifier to ‘Protected’. Meaning that only one assembly affected.
4 zeff 11 August 2008 @ 8:27 pm
Sorry .. access-modifier ‘Internal’
Comments: