Rosdi Kasim Rosdi Kasim - 2 months ago 7
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) {
str.Append(value);
}

return GenerateMd5Hash(str.ToString());
}


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

Answer

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.