Rosdi Kasim Rosdi Kasim - 3 months ago 10
C# Question

Will C# compiler optimize this code by converting the var to const?

Assuming I have this function:

public string GenerateHash(string[] values)
var secureSecret = "a secret string"; //<-- this can/should be const

var str = new StringBuilder(secureSecret);
foreach (var value in values) {

return GenerateMd5Hash(str.ToString());

Clearly the
above can be
, should I bother changing this to
or the compiler is smart enough to know this?


If you look at the generated IL, you can see the compiler doesn't create a new string, it simply calls ldstr:

IL_0001:  ldstr       "a secret string"

The compiler is smart enough to "bake" this constant string into the generated DLL/executable you're creating.

Having said that, using a const conveys the writers intention, and adds to clarity to the code and enhances maintainability IMO. It will later allow you to refactor those "magic" strings more easily instead of sprinkling them everywhere in your codebase.