142

Having a friendly debate with a co-worker about this. We have some thoughts about this, but wondering what the SO crowd thinks about this?

6
  • Do you any other languages have this feature? It seems obvious. Commented Jul 7, 2015 at 15:00
  • 10
    @ColonelPanic C and C++ have const local variables, which you can initialize with a runtime-computed value.
    – Crashworks
    Commented Jan 9, 2016 at 11:08
  • 6
    JavaScript 2015 (ES6) has const type. E.g. { const myList = [1,2,3]; }. It's very good programming practice to use this construct. More info: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – andrew.fox
    Commented Jan 18, 2016 at 9:20
  • 5
    Update 2017: Please vote for the feature request under discussion in the C# Language Design repo! github.com/dotnet/csharplang/issues/188 Commented Dec 6, 2017 at 10:21
  • 1
    I just got hit by a bug because this doesn't exist. Someone modified a variable that should have been a const and rekked a loop... how many thousands of hours have been lost debugging because .net does not have this simple feature?
    – Brain2000
    Commented Mar 1, 2023 at 20:27

12 Answers 12

97

I think it's a poor judgement on part of C# architects. readonly modifier on local variables helps maintain program correctness (just like asserts) and can potentially help the compiler optimize code (at least in the case of other languages). The fact that it's disallowed in C# right now, is another argument that some of the "features" of C# are merely an enforcement of personal coding style of its creators.

3
  • 18
    I agree on the "save the programmer from himself" part, but as for helping the compiler to optimize code, I hold the stance that the compiler can find out very well whether or not a variable changes over the course of the method and optimizes accordingly either way. Placing a 'readonly' flag before something the optimizer recognizes anyways for that purpose does not really benefit, yet potentially mislead.
    – Cornelius
    Commented May 10, 2011 at 12:37
  • 2
    @Cornelius I agree that there are opinions that in some cases the compiler uses data-flow diagram to figure out optimization opportunity regardless of any keyword/modifiers. But saving the programmer from himself from writing incorrect and otherwise unnecessarily unoptimized code may open up that optimization opportunity for compiler.
    – KRoy
    Commented Nov 16, 2018 at 19:37
  • Don't modern compilers perform Static Single Assignment anyway? In which case it's moot as far as optimizations are concerned (but if a compiler supports SSA then it means it's also trivial to implement assign-once local variables).
    – Dai
    Commented May 3, 2020 at 6:59
57

A proposal readonly locals and parameters for was briefly discussed by the C# 7 design team. From C# Design Meeting Notes for Jan 21, 2015:

Parameters and locals can be captured by lambdas and thereby accessed concurrently, but there's no way to protect them from shared-mutual-state issues: they can't be readonly.

In general, most parameters and many locals are never intended to be assigned to after they get their initial value. Allowing readonly on them would express that intent clearly.

One problem is that this feature might be an "attractive nuisance". Whereas the "right thing" to do would nearly always be to make parameters and locals readonly, it would clutter the code significantly to do so.

An idea to partly alleviate this is to allow the combination readonly var on a local variable to be contracted to val or something short like that. More generally we could try to simply think of a shorter keyword than the established readonly to express the readonly-ness.

Discussion continues in the C# Language Design repo. Vote to show your support. https://github.com/dotnet/csharplang/issues/188

6
  • could also make readonly the default (via some option or keyword or whatever). most variables and parameters should be readonly, with only a few writable. and minimizing the number that are writable is generally a good thing. Commented Feb 6, 2020 at 20:02
  • 2
    Could also use let or const. Commented Apr 20, 2021 at 14:33
  • const has a very specific meaning. Using val (like Scala) or let would be a better option. Commented Aug 25, 2022 at 14:04
  • @DaveCousineau making variables read only by default would need additional keyword (such as mutable in F#) to have them modifiable. I think the change would be as big as introduction of #nullable.
    – Endrju
    Commented Jan 3, 2023 at 19:55
  • I feel like val would look too similar to var and should not be used. let seems viable. one or once could also be used, since semantically a readonly local is assigned a value once and that's it. It would look like this : int once Foo = 10;. To preserve backwards compatibility it would be a contextual keyword.
    – Scover
    Commented Dec 25, 2023 at 22:59
28

Addressing Jared's answer, it would probably just have to be a compile-time feature - the compiler would prohibit you from writing to the variable after the initial declaration (which would have to include an assignment).

Can I see value in this? Potentially - but not a lot, to be honest. If you can't easily tell whether or not a variable is going to be assigned elsewhere in the method, then your method is too long.

For what it's worth, Java has this feature (using the final modifier) and I've very rarely seen it used other than in cases where it has to be used to allow the variable to be captured by an anonymous inner class - and where it is used, it gives me an impression of clutter rather than useful information.

26
  • 86
    There's a difference between seeing whether or not a variable is modified in your method by sight and by the compiler. I see no objection to writing a method, stating my intent to not modify a variable, and having the compiler notify me when I accidentally do (perhaps with a typo a month later)!
    – A. Rex
    Commented Jan 14, 2009 at 18:06
  • 55
    On the other hand, in F# all variables are read-only by default, and you have to use the 'mutable' keyword if you want to be able to change them. Since F# is a .NET language, I imagine it does the compile-time checking you describe. Commented Jan 14, 2009 at 18:43
  • 7
    FWIW, Scala distinguishes local readonly/final values from variables with its val and var keywords. In Scala code, local vals are used very frequently (and are, in fact, preferred over local vars). I suspect that the primary reasons that the final modifier is not used more frequently in Java are a) clutter and b) laziness. Commented Jun 20, 2014 at 16:51
  • 6
    For local variables that aren't used in closures, readonly wouldn't be overly important. On the other hand, for local variables which are used in closures, readonly would in many cases let the compiler generate more efficient code. Presently, when execution enters a block which contains a closure, the compiler must create a new heap object for the closed-over variables, even if no code which would use the closure is ever executed. If a variable were read-only, code outside the closure could use a normal variable; only when a delegate is created for the closure...
    – supercat
    Commented Mar 4, 2015 at 21:32
  • 5
    The experience of writing javascript using const made me look for this in c#. I've always been missing c# features when writing javascript. This is the first time I've been missing javascript features in c#.
    – Sam Sippe
    Commented Oct 4, 2017 at 23:12
22

It is an oversight for c# language designer. F# has val keyword and it is based on CLR. There is no reason C# can't have the same language feature.

1
  • C# clearly needs a keyword to initialize local constants at runtime, a keyword where you can specify the type or have it be inferred like var. Except that the inferred type should be non-nullable IMO.
    – Rivenfall
    Commented Mar 16, 2023 at 14:41
13

One reason is there is no CLR support for a readonly local. Readonly is translated into the CLR/CLI initonly opcode. This flag can only be applied to fields and has no meaning for a local. In fact, applying it to a local will likely produce unverifiable code.

This doesn't mean that C# couldn't do this. But it would give two different meanings to the same language construct. The version for locals would have no CLR equivalent mapping.

6
  • 72
    It actually has nothing to do with CLI support for the feature, because local variables are in no way exposed to other assemblies. The readonly keyword for fields needs to be supported by the CLI because its effect is visible to other assemblies. All it would mean is the variable only has one assignment in the method at compile time. Commented Sep 3, 2009 at 2:06
  • 22
    I think you've just shifted the question to why the CLR does not support this rather than providing the rational behind it. It does allow for const locals, so it would be reasonable to expect readonly locals as well. Commented Aug 16, 2012 at 16:25
  • 11
    An example of this are variable defined in a using statement. They are local ... and readonly (try to assign them, C# will add an error).
    – Softlion
    Commented Nov 16, 2013 at 10:46
  • 10
    -1 In C++ there's no machine code support for const (which in C++ is more like C# readonly than like C# const, although it can play both roles). Yet C++ supports const for local automatic variable. Hence the lack of CLR support for a C# readonly for local variable, is irrelevant. Commented Jun 14, 2014 at 13:00
  • 10
    1. This can easily be a compiler feature, like in C++. CLR support is completely irrelevant. Machine assembly doesn't support it either, so what? 2. (it would) likely produce unverifiable code - I don't see how, but perhaps I am mistaken. 3. it would give two different meanings to the same language construct - I doubt anyone would see this as an issue, since using and out are doing exactly that and the world didn't collapse.
    – Lou
    Commented Mar 15, 2017 at 10:28
8

I was that coworker and it wasn't friendly! (just kidding)

I would not eliminate the feature because it's better to write short methods. It's a bit like saying you shouldn't use threads because they're hard. Give me the knife and let me be responsible for not cutting myself.

Personally, I wanted another "var" type keyword like "inv" (invarient) or "rvar" to avoid clutter. I've been studying F# as of late and find the immutable thing appealing.

Never knew Java had this.

4

I would like local readonly variables in the same manner as I like local const variables. But it has less priority than other topics.
Maybe its priority is the same reason for C# designers to not (yet!) implement this feature. But it should be easy (and backward compatible) to support local readonly variables in future versions.

0

I know, this doesn't answer the why to your question. Anyway, those reading this question might appreciate the code below nonetheless.

If you are really concerned with shooting your self in the foot when overriding a local variable that should only be set once, and you don't want to make it a more globally accessible variable, you could do something like this.

    public class ReadOnly<T>
    {
        public T Value { get; private set; }

        public ReadOnly(T pValue)
        {
            Value = pValue;
        }

        public static bool operator ==(ReadOnly<T> pReadOnlyT, T pT)
        {
            if (object.ReferenceEquals(pReadOnlyT, null))
            {
                return object.ReferenceEquals(pT, null);
            }
            return (pReadOnlyT.Value.Equals(pT));
        }

        public static bool operator !=(ReadOnly<T> pReadOnlyT, T pT)
        {
            return !(pReadOnlyT == pT);
        }
    }

Example usage:

        var rInt = new ReadOnly<int>(5);
        if (rInt == 5)
        {
            //Int is 5 indeed
        }
        var copyValueOfInt = rInt.Value;
        //rInt.Value = 6; //Doesn't compile, setter is private

Maybe not as less code as rvar rInt = 5 but it works.

2
  • That doesn't help here. This issue with variable 'var' is: { var five = 5 five = 6; Assert.That(five==5) }
    – Murray
    Commented May 10, 2017 at 7:52
  • 1
    the same problem, because we still can: rInt = new ReadOnly<int>(15);
    – Lealan
    Commented Jan 22, 2022 at 20:54
-1

You can declare readonly local variables in C#, if you're using the C# interactive compiler csi:

>"C:\Program Files (x86)\MSBuild\14.0\Bin\csi.exe"
Microsoft (R) Visual C# Interactive Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.

Type "#help" for more information.
> readonly var message = "hello";
> message = "goodbye";
(1,1): error CS0191: A readonly field cannot be assigned to (except in a constructor or a variable initializer)

You can also declare readonly local variables in the .csx script format.

1
  • 9
    Per the error message, message is not a variable here, it's compiled to a field. This is not nitpicking because the distinction clearly exists in interactive C# as well: int x; Console.WriteLine(x) is legal interactive C# (because x is a field and implicitly initialized) but void foo() { int x; Console.WriteLine(x); } is not (because x is a variable and used before it's assigned). Also, Expression<Func<int>> y = x; ((MemberExpression) y.Body).Member.MemberType will reveal that x is really a field and not a local variable. Commented Jul 12, 2016 at 15:32
-1

Being able to make local variables readonly makes it a lot easier to understand complicated algorithms, since it reduces the number of moving parts.

Since C# doesn't offer it natively for non-compile time constants I use this with implicit casts:

public readonly struct ReadonlyVar<T>
{
    private readonly T value;

    internal ReadonlyVar(T _value) => value = _value;

    public static implicit operator T(ReadonlyVar<T> _readonly) => _readonly.value;

    public override string ToString() => "" + value;
}

public static class ReadonlyExt
{
    public static ReadonlyVar<T> Readonly<T>(this T _value) => new ReadonlyVar<T>(_value);
}

Usage:

int y = 234;
var x = ( 9000 + y ).Readonly();
y = x;

It is not perfect, since it is possible to assign another ReadonlyVar to it, but this never happened to me unintentionally.

6
  • Hi Christian - I don't think this is actually an answer to the question. It seems the question is "I wonder why C# doesn't natively support this, any thoughts?" rather than a "how would one do this?" Javascript now has both a "let" and a "const", but c# has nothing equivalent to "const", and this question wonders why.
    – pettys
    Commented Sep 13, 2021 at 21:47
  • This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
    – pettys
    Commented Sep 13, 2021 at 21:48
  • 5
    Hi pettys, the author indeed didn't ask how do this, but this thread is the first and only on stackoverflow when I search for "c# readonly local variable". I guess that most people, like me, arrive here, because they want that feature. Since it is less than 10 lines of code, it's even less reason for Microsoft to change the compiler for a feature that might not be important in their opinion. Commented Sep 13, 2021 at 22:40
  • 1
    This doesn't actually make the variable readonly at all. In your own usage code you can just write x = 42.ReadOnly(); and you have mutated the variable. This code ads complexity without adding any actual functionality. It's also off topic to the question, as others have said, but it's not useful anyway.
    – Servy
    Commented Sep 13, 2021 at 23:11
  • 1
    That's right, Servy. :) But so far I never happened to me unintentionally. I often make local variables readonly to make complicated algorithms easier to understand. At least for me it is a very useful tool to have. Commented Sep 14, 2021 at 6:11
-5

use const keyword to make read only variable.

reference: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const

public class SealedTest
{
    static void Main()
    {
        const int c = 707;
        Console.WriteLine("My local constant = {0}", c);
    }
}
1
  • 4
    We’re interested in JavaScript-style const where the variable may only be assigned during its initialization—not csharp-style const where only compile-time expressions may be used. E.g., you can’t do const object c = new object(); but a readonly local would allow you to do this.
    – binki
    Commented Dec 22, 2017 at 19:10
-9

I think that's because a function that has a readonly variable may never be called, and there's probably something about it going out of scope, and when would you need to?

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