Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


C# (C sharp): Microsoft FAQ

Code Examples

public const vs. public static readonly by chiph
Posted: 14 Jul 06 (Edited 18 Jul 06)

Here's something that people might not know:
When defining public constants in classes, it's very tempting to use:

public const string FLD_STATE = "State";

However, when this constant is referenced in another assembly, the C# compiler will replace the call to this constant with the value itself:

L_00f0: ldstr "State"
L_00f5: callvirt instance void [MyAssem]MyAssem.MyClass::MyMethod(string)

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:

public static readonly string FLD_AREAID = "AreaId";

When compiled, the compiler will not inline this string literal, so you get MSIL code that looks like this:

L_00b9: ldsfld string MyBizAssem.MyBizClass::FLD_AREAID
L_00be: callvirt instance void [MyAssem]MyAssem.MyClass::MyMethod(string)

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.

Back to C# (C sharp): Microsoft FAQ Index
Back to C# (C sharp): Microsoft Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close