TransWikia.com

Why use const in C#?

Software Engineering Asked on October 29, 2021

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?

One Answer

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

Answered by Sebastian Redl on October 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP