What if we will not use "this"?

Without having any different scenario then this

“when this constructor is used to make a new instance, use the argument area to set the value of this new instance’s Area field”.

it is very hard to understand.

In other words what can it lead to if we will not use this?

The parameter for the constructor area looks a lot like the old field area and the new property Area . It’s good to be explicit when writing code so that there is no room for misinterpretation. We can refer to the current instance of a class with the this keyword.

class Forest{
  public int Area  
{ /* property omitted */ }   

public Forest(int area)  
{   
 this.Area = area;  
}

`> Blockquote`

}

this.Area = area means “when this constructor is used to make a new instance, use the argument area to set the value of this new instance’s Area field”.

Hi,

this is an explicit reference to the object’s instance. What does that mean? Let’s break it apart:

  • an instance of an object is a unique declaration of a class in memory. For example, in a program with class Fruit, you may have the objects apple, orange, pear doing different things. They are each class Fruit but occupy a dedicated space in memory (whereas as class Fruit is just a template for these).

  • what is an explicit reference? In the the code for class Fruit, when we write code that affects the data of that class, we are actually writing code that affects specific instances of that class, not the template itself. So whenever we write price_of_fruit = price we must be referring to a specific fruit, not the general class itself. That’s why we use this. The explicit bit means we point at the specific fruit.

  • so if we say this.price= price. Every time the compiler interprets it, in a high-level perspective it will think “apple.price = 2”, “orange.price = 4” and so forth. (The price will vary for each fruit of course

1 Like