Const string field vs "typed" string

I have a small function that looks something like this:

void Bar(string s) { */ do somthing with the string here.*/ } void Foo() { Bar("Hello"); } 

If I look at the output of IL, it gives me the following:

 .method private hidebysig instance void Foo() cil managed { .maxstack 8 L_0000: ldarg.0 L_0001: ldstr "Hello" L_0006: call instance void TestApp.MainWindow::Bar(string) L_000b: ret } 

now I thought I would replace it with a const string field for it.

 const string str= "Hello"; void Foo() { Bar(str); } 

which converts to the EXACT MOST IL fragment.

Now my question is which one to use?

Foo("Hello"); or Foo(cHello);

Thank you for your help!

-------------- EDIT -------------------
To be more specific, I use this for logging to add a prefix to the message: And it will only appear in the code!

so that it looks something like this:

 void LogDebug(string msg) { Log("[DEBUG]", msg) } void Log(string pre, string msg) { // generates an output in form of // pre + msg } 

:)

+4
source share
3 answers

The answer should be obvious: since IL is one and the same, use everything that works best based on pure source codes.

In general, this means that you go with a const string so as not to have a magic value in your Foo method. If a constant is used only once, this may not seem very convincing, but if it is possible to use it more than once in the future, then DRY is largely a shotgun argument.

Update:

In this particular case (debug output, constant guaranteed to be used only once). I do not think the constant provides any value. I hard-coded a string literal.

+5
source

replace const with compilation time in code. This is better if you use a const string instead of a coded lowercase string, as it simplifies their support.

+3
source

(1) Use the string const for private or internal code if this makes the code more readable or you have the same line more than once.

(2) DO NOT PUBLICALLY SUBJECT TO DESIGNS. Use properties instead. (In particular with regard to strings.)

The reason for this is that it binds const closely to assemblies that reference it.

See here to learn more about this:

https://softwareengineering.stackexchange.com/questions/132747/is-having-public-constants-bad

0
source

Source: https://habr.com/ru/post/1469201/


All Articles