Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The "right" answer, in my opinion, depends on how and why you're using the string.</p> <p>If the string is being used for display, or presented to a user, then the property is a better design. This makes it much easier to add localization later by moving the constant into resource files, without having to change your API. This also makes it easier to adapt your class without breaking other code, since you are free to change the "constant" at any time without breaking other assemblies.</p> <p>I rarely find appropriate uses for the second case - very few strings are truly constant, and when they are, I believe they're typically better represented as an enumeration instead of a string. This is almost always better than "magic strings" in your code.</p> <p>The rare exceptions are typically when interacting with legacy code - if you're dealing with a separate API that is expecting a string, and the string is truly constant, than using a constant is potentially "better", in that it is more efficient and very clear in its intent.</p> <p>Also, remember that the two approaches can be used together:</p> <pre><code>private const string employeeString = "Employee"; public string EmployeeString { get { return employeeString; } } </code></pre> <p>This allows you to use the constant, making it's intent clear, but easily change this out later without breaking other code or changing your API. (I personally prefer this to your "second" option above, since the magic string in the property getter is a code smell to me - I like my constants to be obvious constants, but still prefer properties.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload