0

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?

enkryptor
  • 1,574
  • 1
  • 17
  • 27
  • This is for memory and performance boost – apomene Jul 28 '17 at 10:44
  • @Rafalon It's a `get`-only property – Benjamin Hodgson Jul 28 '17 at 10:45
  • When a constant isn't a constant, you could decide not to use a constant. When it is, there's no reason not to use a constant. I have, in my years of .NET development, almost never considered performance as any reason to decide between a property or a constant. – Jeroen Mostert Jul 28 '17 at 10:48
  • Another thing you can do with the static property but not with the const is to localize your `Greetings`. With the const your stuck with the english hello. Use a const only if you are 100% sure that this will never,ever change. – Tim Schmelter Jul 28 '17 at 10:48
  • @TimSchmelter the linked duplicate actually doesn't answer the "when should I use a constant" question. It only explains technical differences between `const` and `static`. – enkryptor Jul 28 '17 at 11:28
  • Having your question closed as a duplicate is one way. The alternative would be to have it closed as opinion-based. The linked question provides you with the technical details on constants vs. properties, which allows anyone to make an informed choice in whatever situation they're considering one or the other. The rest is anecdotes and opinions. – Jeroen Mostert Jul 28 '17 at 11:35

0 Answers0