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.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.