I don't understand the following:
In the code found below, Visual Studio tells me, that I can simplify my code by deleting the second this
keyword in the constructor.
But why can't then I do away with the first this
keyword?
Both variables were declared outside the constructor, in the class, so both will be "overridden"* for the instance.
If I remove both this
keywords, then VS will complain that the first assignment is made to same variable, but not for the second.
The only obvious difference to me is the second variable is an array, but I do not understand how would that make it any different?
*I suspect override is not the correct term here.
public class CelestialObject {
CelestialBody[] celestialBodies;
int celestialBodyCount;
public CelestialObject(int celestialBodyCount = 2) {
this.celestialBodyCount = celestialBodyCount;
this.celestialBodies = new CelestialBody[celestialBodyCount];
}
}
The difference is that you've got a parameter called celestialBodyCount
- which means that within the constructor, the identifier celestialBodyCount
refers to the parameter, so to access the field you have to qualify it with this
.
You don't have a parameter (or other local variable) called celestialBodies
, so that identifier already refers to the field, without any qualification required.
See more on this question at Stackoverflow