?? Why No readonly Local Variables ??

Hi all,

I've looked at what the C# spec has to say and indeed it indicates the readonly keyword can only be applied to fields (not to local variables).

I can see a use for doing this, however. I was wondering if anyone knows the rationale for not allowing readonly to be applied to local variables. It seems like it could be useful.

Thanks.



Answer this question

?? Why No readonly Local Variables ??

  • Bagles1

    "Well a field can never be local by definition. But I don't see why they couldn't allow readonly on locals as well if they wanted. They can certainly be initialized at declaration."

    Because then it would be a const. The ONLY difference would be it would only allow primitive types (as you mention in your second argument). And again, the usefullness of this would be very limited.



  • poo

    Brendan Grant wrote:

    Given this behavior... there really is no way that a readonly field could be local to a method.

    Well a field can never be local by definition. But I don't see why they couldn't allow readonly on locals as well if they wanted. They can certainly be initialized at declaration.

    Brendan Grant wrote:

    If you need such a thing, use const instead.

    The problem with const here is that it doesn't work for all types. Only for primitive types and reference types (where null is the only value you can assign to it).



  • David77

    Java has this behavior with the 'final' keyword; there you can make locals final to allow using them in anonymous classes. In C# you can use locals in anonymous delegates without this restriction. Other than that there really isn't really any other use for it imo.


  • VB Worker

    While readonly is very similar to const in appearance, what they end up doing is very different.

    Lets not forget that a const is evaluated at compile time and can only be initialized at the time of declaration... a readonly value on the other hand is evaluated at runtime and can be initialized at declaration or within the class constructor.

    Given this behavior... there really is no way that a readonly field could be local to a method. If you need such a thing, use const instead.



  • prog

    While I can understand why some users may think this could be useful, I don't really think this will buy you any value in most situations. IMHO, any method that would benefit from this, probably needs refactoring.



  • ?? Why No readonly Local Variables ??