C # What is the difference between these two keywords in the constructor below?

I do not understand the following: In the code below, Visual Studio tells me that I can simplify my code by deleting the second keyword thisin the constructor.

But why can not I give up the first keyword this? Both variables were declared outside the constructor in the class, so both instances will be "overridden" * for the instance.

If I delete both words this, then VS will complain that the first assignment is for the same variable, but not for the second. The only obvious difference for me is the second variable is an array, but I don't understand how this could change?

* I suspect that redefinition here is not correct.

public class CelestialObject {

    CelestialBody[] celestialBodies;
    int celestialBodyCount;

    public CelestialObject(int celestialBodyCount = 2) {
        this.celestialBodyCount = celestialBodyCount;
        this.celestialBodies = new CelestialBody[celestialBodyCount];
    }
}
+4
3

this, , celestialBodyCount:

int celestialBodyCount; // The field

public CelestialObject(int celestialBodyCount = 2) { // The parameter.

this , . , 3.7.1 :

... , , . .

3.7.1.1 :

, , , .

celestialBodyCount celestialBodyCount.

, this, :

Assignment made to same variable; did you mean to assign something else?

.

+5

, celestialBodyCount - , celestialBodyCount , this.

( ) celestialBodies, - .

+3

this :

public CelestialObject(int celestialBodyCount = 2) 
{
    celestialBodyCount = celestialBodyCount;
    this.celestialBodies = new CelestialBody[celestialBodyCount];
}

Visual Studio : ", this celestialBodyCount, , . , ? ?" Visual Studio , celestialBodyCount , . Visual Studio, .

this.celestialBodyCount, Visual Studio , .

this.celestialBodies , , this.

+2

Source: https://habr.com/ru/post/1665426/


All Articles