Stupid .NET Tricks #13
May 21, 2008 2:04 pm programmingIn Java, making a field “final” means that you can only assign a value to it once. It’s an important part of making a class immutable. It helps to prevent bugs too: make a field final and you’ll get a compiler error if you leave it unassigned or try to reassign it anywhere.
.NET has a similar concept with the “readonly” keyword for fields. However, there’s one important difference compared to Java: a “readonly” field can only be assigned in the class’s constructor, but it can be assigned multiple times within that constructor. The only restriction it places is that the field can’t be reassigned outside of the constructor. You don’t even get a compiler error for not assigning it at all; you only get a compiler warning (which can be turned off).
This has encouraged bugs at least twice in my code: I assigned a value to a field twice within the constructor and then got unexpected results due to the incorrect object being used. One of these was caused by a conflict resolution from a Subversion Merge (and thus it was less-than-obvious that it had been introduced).
