Why does C# disallow readonly local variables? [closed]
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?
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.
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