1

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?

2
  • 2
    semi-offtopic: i would point out that anyone looking at your dll/exe in for example ILSpy / ildasm etc can trivially read your 'secureSecret' so you might want to ask a separate question about hiding/obfuscating strings! Commented Sep 26, 2016 at 11:42
  • @tolanj, Understood.. and good point. But I just made up the code snippet above... in my case I am actually auditing huge legacy codes and getting tons of warnings saying 'variables can be made constant'... none of it actually poses security risk. Commented Sep 26, 2016 at 18:25

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Got to learn this weird IL thing... looks interesting. Btw I am currently auditing huge legacy codes and there are hundreds (maybe thousands) of warning 'variable can be made constant'..., so it is probably not worth the effort fixing this.
@RosdiKasim It's not weird, it's actually quite nice :). You get to see under the covers, which is always a good thing to learn.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.