Search code examples
c#immutabilitylanguage-designreadonly

Why does C# disallow readonly local variables?


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?


Solution

  • 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.