2

Consider these three examples:

Example A

string message = "Hello world!";
throw new System.Exception(message);

Example B

const string message = "Hello world!";
throw new System.Exception(message);

Example C

throw new System.Exception("Hello world!");

Is there any reason to use one over the others? Specifically, shouldn't I try to use const string where possible (assuming the string is never modified), and therefore Example B is best? What happens in Example C?

I guess I'm asking if the IL emitted by the above are identical or different, and if there is any difference. I recognize that the difference will be small and probably not anything to worry about; I guess that makes this an academic question.


Edit. Here's the IL

IL_0014: ldstr "This is a string"
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0020: throw


IL_0033: nop
IL_0034: ldstr "This is a const string"
IL_0039: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_003e: throw

IL_0051: nop
IL_0052: ldstr "This is an inline string."
IL_0057: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_005c: throw

Looks substantively identical to me.

4
  • grab a decompiler and go to town! Commented Nov 7, 2013 at 20:47
  • I fail to understand why you don't just look at the IL and decide for yourself? With the right compiler options, they should come out the same, actually. Commented Nov 7, 2013 at 20:47
  • 1
    The question is an unrealistic apples and oranges comparison. B can only be a field. A can be a field or a local variable. C can only be declared inline. Commented Nov 7, 2013 at 20:55
  • 1
    You can do B in a method, but I normally only use as fields myself. Commented Nov 7, 2013 at 20:57

2 Answers 2

1

depends on context, really. is this message ever going to change? If you use option A, you have the opportunity to modify the value of string message, with the other two you're printing a hard coded string - which is fine, if it's always going to say just that

Sign up to request clarification or add additional context in comments.

Comments

0

There is no difference in terms of performance, memory use, or string table efficiency.

The only effect of the const keyword is to generate a compile time error when the string is re-assigned. So it is helpful to add const to communicate your intention to other developers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.