Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top