0

What's the point of ever using const?

It is more restrictive than static readonly:

  • across assemblies, changes to a constin a dependency won't be reflected in its consumers
  • you can only use const for certain primitive types

with both these restrictions in mind, perhaps among others I am not aware of, why ever use const?

Why not always use static readonly to maintain consistency of style?

  • 3
    See here and here. – Robert Harvey Jul 19 at 17:34
  • @RobertHarvey I have done a little research, and I'm aware of at least most of the most well-known differences. But from reading those, it now seems like const is less versatile and has no positives in its favor... – theonlygusti Jul 19 at 18:48
  • You'll find a decent explanation of when to use which here. – candied_orange Jul 19 at 19:22
  • @candied_orange It still doesn't give any reason to actually use const over static readonly... it just describes what const stops you from doing – theonlygusti Jul 19 at 20:14
  • The point of all high level languages is what they stop you from doing. – candied_orange Jul 19 at 20:16
9

Things declared const are true compile-time constants, and thus may occur in constant-expressions. This means you can use them in the following contexts, where static readonly variables may not appear[1]:

  • Values of other constants: const int OTHER = N;
  • Explicit values of enum members: enum Foo { Bar = N }
  • Default arguments: void Fn(int i = N)
  • case labels: case N: and goto case N;
  • Attribute values: [Value(N)]
  • (rather irrelevant) array creation with initializers: new int[N] { 1, 2, 3 }

[1] https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#constant-expressions

| improve this answer | |
  • Very good answer, thank you. Why is the array creation one "rather irrelevant" in your opinion? – theonlygusti Jul 19 at 21:18
  • 1
    Very good answer but the first bullet point is kind of irrelevant (+1 nonethelesss). If you use static readonly instead of const, you won't be trying to assign to any consts either. – Flater Jul 19 at 22:19
  • Using the const in an array creation expression is meaningless because you can omit the explicit size and the compiler will implicitly size the array by the size of the initializer list. – Avner Shahar-Kashtan Jul 20 at 5:23
  • @theonlygusti Pretty much what Avner said. I think you can write new[MORE_THAN_THREE] { 1, 2, 3 } and the additional elements are default-initialized, but I don't know when that use case ever comes up, except perhaps in a prime filter toy. – Sebastian Redl Jul 20 at 9:59
  • @SebastianRedl no, this doesn't compile (Error CS0847) – Bill Tür Jul 20 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.