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.

?? Why No readonly Local Variables ??
Ueslei
"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.
Greg.Duffield
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.
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).
newb821
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.
Stigmata
hjy
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.