In C#, you define a constant like this:
private const string Greetings = "Hello!";
Later in the code instead of the string "Hello!" you use the constant:
Console.WriteLine(Greetings);
However, Greetings
doesn't have to be a constant to work properly in this example. It also can be a static property:
private static string Greetings { get; } = "Hello!";
This gives you more flexibility:
- The property can be any type, not only a compile-time constant
- Later you can freely implement any logic in the getter
- Modern IDEs (like VS) shows the property references, which is handy
As far as i understand, a constant works faster than a static property, since Console.WriteLine(Greetings)
being compiled produces exactly the same result as just Console.WriteLine("Hello!")
.
But people often use constants to store many things where the speed is not an issue, like initial application state, or subtle developers' settings like timeout intervals.
Besides from the optimization purposes, when should I use a constant and not a static property?