2

Is there a C# equivalent of JS ES6's 'const' for declaring local variables that don't change value?

I know there is a 'const' keyword in C# but this isn't the same thing, as the value of this can only be set at compile time, not runtime.

I have found the ES6 const useful for making JS easier to read. Like seeing something declared as 'const' tells me that this is something that doesn't change. Likewise something declared as 'let' tells me that this is expected to change.

MakkyNZ
  • 2,215
  • 5
  • 33
  • 53

2 Answers2

3

C# does not have a way to declare local variables as immutable (well, you can in a query comprehension, but that really doesn't count).

You can, however, declare the field of a class to be immutable using the readonly keyword (or, equivalently, by declaring read-only auto-implemented property). Such fields can only be (re)assigned in a constructor.

Rodrick Chapman
  • 5,437
  • 2
  • 31
  • 32
  • There are other exceptions, such as the loop variable of a `foreach` loop. – Servy Aug 10 '17 at 21:47
  • Can you post some example code for that @Servy in an answer? _I wasn't aware loops had immutable variables._ – mjwills Aug 10 '17 at 21:58
  • @mjwills – Specifically, the *iteration variable* in a `foreach` is immutable (e.g in `foreach (var n in …)`, the variable n is immutable within the body of the loop). Similarly, variables declared by the `using` statement are also immutable. – Rodrick Chapman Aug 11 '17 at 03:35
1

Try the readonly keyword

Readonly Keyword MSDN

Dan D
  • 2,493
  • 15
  • 23