Why does C# disallow readonly local variables?

后端 未结 13 1290
萌比男神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:57

    c# already has a readonly var, albeit in a somewhat different syntax:

    Consider the following lines:

    var mutable = myImmutableCalculationMethod();
    readonly var immutable = mutable; // not allowed in C# 8 and prior versions
    return immutable;
    

    Compare with:

    var mutable = myImmutableCalculationMethod();
    string immutable() => mutable; // allowed in C# 7
    return immutable();
    

    Admittedly, the first solution could possibly be less code to write. But the 2nd snippet will make the readonly explicit, when referencing the variable.

提交回复
热议问题