Const in referenced assembly becomes literal in compiled code

  • Thread starter Sledgehammer777
  • Start date
S

Sledgehammer777

I have an issue that I'd like some oone to explain to me. In a C# DLL
I have a several const strings defined as such:

namespace ns
{
public class strings
{
public const string string1 = "XYZ";
public const string string2 = "ABC";
}
}


Now, in another file I have some code like this:

string code = ns.strings.string1;


Now when I compile my code and then disassemble it I see this:

string code = "XYZ";



I understand the compiler could change the reference to the literal
for optimization purposes but the problem then occurs when I change
the code in the DLL and deploy the DLL without recompiling the app,
the change is not picked up in the app because the reference is lost.

Is this by design and is there a way around it?
 
N

Nicholas Paldino [.NET/C# MVP]

Yes, it is by design. I mean, you are declaring it as a ^constant^
which has a certain implication. If these values can change between
compilation (which means that it definitely is not constant), then you
should make the declaration as public, static, and readonly.

Constant is intended for natural constants, things that will never, ever
change.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top