I am not a Java programmer. I read the documentation on “final”, and understand it to mean “a variable’s value may be set once and only once.”
I am translating some Java to C#. The code does not execute as expected. I tried to figure out why, and found some uses of final that don’t make sense.
Code snippet 1:
final int[] PRED = { 0, 0, 0 };
...
PRED[1] = 3;
Will PRED[1] be 0 or 3?
Code snippet 2:
final int[] PRED = new int[this.Nf];
for (int nComponent = 0; nComponent < this.Nf; nComponent++) {
PRED[nComponent] = 0;
}
...
PRED[1] = 3;
Surely PRED[0] will remain as 0?
I think you have a misunderstanding of the
finalkeyword semantic when it is applied to arrays in Java.In both Java examples the arrays will remain unchanged, but their elements may be changed. All your assignments will be executed correctly, and the values stored in the array will get changed. However, if you try
you are going to see a compile error.
When translating your code to C#, you may need to translate
finaleither assealed(when it is applied to aclass), or asreadonly(when it is applied to a member). The semantic ofreadonlyarrays in C# andfinalarrays in Java are the same: your program cannot reassign the array, but it can freely modify its elements.Finally, there is a Java-specific case when
finalis used where you wouldn’t need it in C# at all: when you need to use a variable inside a method of an anonymous local class in Java, you must make that variablefinal. Since C# does not have anonymous local classes, you would need to translate that piece of code with something else, perhaps with anonymous delegates. Such delegates are not restricted to using readonly variables.