The c# const keyword is great. At compile time, the contant is actual replaced by the actual string anywhere that the constant is referenced. The compiler just does a find/replace. This is great for private and internal constants. If ever the constant changes (and it might), it’s replaced when the assembly is rebuilt. If you use the contant 50 times in your code. Use Lutz Roeder’s Reflector to look at one of your assemblies that references these contants. You won’t find the constant name. You will actually find the string that the constant was set to. This is the optimization benefit fo constants.
Now, what happens when you have a public constant, and you reference it from a client assembly? Same thing. The compiler takes the value of the constant and replaces it with the literal string. 100% optimized. Then, a new version of the shared assembly comes out, and the constant has changed. You drop this new assembly in your app directory and try your application. No dice. Your assembly has the old constant string hard-coded in it. The shared assembly is expecting the new string. Bad situation. You have to recompile the client assembly (hoping that the 5-year old source code is the right copy and that things weren’t misplaced over the years) and completely retest the new build (the cost of that depending on the size of the application).
The good news is that there is a very easy way to prevent this maintenance nightmare: don’t use public constants. Instead, use public static readonly varName. This is a normal variable with the same scope as a public const, but client assemblies reference the variable instead of replacing it with the literal string. Now when the const changes, the client assembly gets the new string through the public static variable.
It only takes a minute to do a global search for “public const” to see if your application might fall prey to this problem. Also, be sure to convert protected constants as well because client assemblies could contain classes that derive from the offending class.