Consider the following two cases:
case 1:
class A { private const string MyConst="Hello"; internal void CallMe() { System.Console.WriteLine(MyConst); } }
Case2:
class A { internal void CallMe() { System.Console.WriteLine("Hello"); } }
Now if the CallMe() method would be called 1000 times, is it a good idea to define it as a constant (which means only one copy of the string per class) or using a plain string would be better. I just checked the MSIL code for both the classes and found that in both cases, .Net compiler is putting the string literal inside WiriteLine(). Then is it an overhead to define the string as a constant?
The main reason I asked this question was because I wanted to understand how CLR works when something is defined as a constant at the class level and when I saw that the MSIL code had const field as well as the string in WriteLine() replaced with the actual string so I was wondering why create constant field if it will be used in only one method. This is just a sample code I wrote to present my doubt.And from the responses I learnt following:
- It's better to use the string directly if it won't be used outside the method
- If it's used throughout the class/classes then declare it as constant at the class level
- Put it in resex if it needs localization
Thanks all for responses/comments.