Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

public const vs. public static readonly

Code Examples

public const vs. public static readonly

by  chiph  Posted    (Edited  )
Here's something that people might not know:
When defining public constants in classes, it's very tempting to use:
[tt]
public const string FLD_STATE = "State";
[/tt]
However, when this constant is referenced in another assembly, the C# compiler will replace the call to this constant with the value itself:
[tt]
L_00f0: ldstr "State"
L_00f5: callvirt instance void [MyAssem]MyAssem.MyClass::MyMethod(string)
[/tt]
What happens when code maintenance operations in the future is that the assembly where the constant is defined gets updated, and the literal gets replaced with a different one. However, any assembly that was originally using it still has the old value.

This may not be a problem for your project if you have daily builds. To get around this (albeit at a performance cost!) you would define it like this:
[tt]
public static readonly string FLD_AREAID = "AreaId";
[/tt]
When compiled, the compiler will not inline this string literal, so you get MSIL code that looks like this:
[tt]
L_00b9: ldsfld string MyBizAssem.MyBizClass::FLD_AREAID
L_00be: callvirt instance void [MyAssem]MyAssem.MyClass::MyMethod(string)
[/tt]
and it will work correctly after MyBizAssem gets recompiled without the assemblies that use MyBizAssem also needing to be recompiled.

The performance cost is that of crossing assemblies. If this is the first time that MyBizAssem is called, the .NET runtime must make various security checks, as well as possibly rebasing the assembly (relocating it in memory to avoid load collisions), which takes time.

Note that private and protected constants don't have this problem, as their scoping/visibility precludes this from happening.

Chip H.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top