DEV Community

Calin Baenen
Calin Baenen

Posted on

Which one is better, Java's `final` or C#'s `readonly`?

Personally, I wish C# had a final keyword.

Why? This:
What everyone here is missing is Java's guarantee of definite assignment for  raw `final` endraw  member variables. For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error. C#'s  raw `readonly` endraw  keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor. So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

Also because there's no local-variable equivalent.

Discussion (0)