C# – Declaring Strings: public static readonly vs public const

c++string

In each project we have there is a file used to store the various SQL statements used in that project. There are a handful of variations on how the class is declared and how the strings are declared.

Example class declartions:

internal sealed class ClassName
internal static class ClassName
public sealed class ClassName
public static class ClassName
internal class ClassName

Example string declarations:

internal const string stringName
internal static string stringName
public static readonly string stringName
public static string stringName
public const string stringName

I don't understand what the performance implications are between the different declarations. Is there a best practice for this situation/scenario?

Best Answer

I don't understand what the performance implications are between the different declarations

The cost of evaluating the database query is probably going to be millions or billions of times the cost difference of changing from a constant to a readonly field or vice versa. Don't even worry about performance of something that takes a couple of nanoseconds when you have database operations that have latency measured in milliseconds.

What you should be worrying about is semantics, not performance. The question boils down to "readonly, constant or neither?"

Get the semantics right. A "readonly" field means "this field changes exactly once per time this program is executed", from null to its value. A "const" field means "this value never changes, not now, not in the next version, not ever, it is constant for all time." An ordinary field can change value at any time.

A readonly field is something like a version number. It changes over time, but does not change over the execution of the program. A constant is something like pi, or the atomic number of lead; it is fixed, eternal, never changes. An ordinary field is good for something that changes over the course of the program, like the price of gold. Which is your query like? Will it be constant throughout the course of this program, constant for all time, or not constant at all?