1

To clarify, is there any downside to initializing a string like this:

public static readonly string myString = nameof(myString);

I've recently come across this method and thought it was quite clever, since you can rename the variable and simultaneously change its value from any place in the code without much hassle.

Obviously, this only makes sense if you want the variables to have the same value as the variable name, but are there pitfalls beyond that?

nvoigt
  • 75,013
  • 26
  • 93
  • 142
M-Expunged
  • 71
  • 1
  • 6
  • 1
    `nameof` is computed at compile time. It's same as making `string MyString = "MyString"`, there's no performance hit. But why do you want to do this? – JL0PD Jun 25 '21 at 10:56
  • 1
    @JL0PD You are right! Just looked it up in the docs, must have overread it the first time, thanks. **A nameof expression is evaluated at compile time and has no effect at run time.** – M-Expunged Jun 25 '21 at 10:59
  • This is a common practice to declare string tokens. You get a refactorable string constant and something that you can check for references in your code base. – Paulo Morgado Jun 26 '21 at 17:49

0 Answers0