In Java, final
means a variable can only be assigned to once, but that assignment can happen anywhere in the program. In C#, readonly
means a field can only be assigned in a constructor, which, IMO, is significantly less useful.
As we all know, C# was heavily influenced by Java design, but this difference has always puzzled me as being very odd. Does anyone know if there's a technical reason in the CLR that resulted in the less-useful behavior of C#'s readonly
vs Java's final
?
EDIT:
In response to the comments; I'd like to point out that I am well aware of the benefits of immutability, and I use it all over the place. I believe readonly
is less useful than Java because of this:
public class Foo
{
private readonly int _bar;
Foo()
{
_bar = 5;
}
}
Whoops, I actually need to initialize that value in a helper method!
public class Foo
{
private readonly int _bar;
Foo()
{
initialize()
}
private void initialize()
{
_bar = 5; //Can't compile because of semantics of readonly
}
}