Why does C# disallow readonly local variables?

后端 未结 13 1168
萌比男神i
萌比男神i 2020-11-27 17:17

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?

相关标签:
13条回答
  • 2020-11-27 17:42

    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 讨论(0)
  • 2020-11-27 17:46

    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.

    0 讨论(0)
  • 2020-11-27 17:47

    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.

    0 讨论(0)
  • 2020-11-27 17:52

    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.

    0 讨论(0)
  • 2020-11-27 17:55

    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.

    0 讨论(0)
  • 2020-11-27 17:57

    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.

    0 讨论(0)
提交回复
热议问题