Question:
What is the real use of using the reserved word this
?
From what I see, it doesn't matter whether you use it or not, but I have doubts about its functionality.
Answer:
this
serves to reference the object itself.
There are cases where its use becomes necessary.
class Pessoa {
private string nome;
public Pessoa(string nome){
this.nome = nome;
}
}
In the example above if I didn't use this
, I would be referring to the parameter and not the class name property.
And others in which its use becomes optional:
class Pessoa {
private string _nome;
public Pessoa(string nome){
// como não existe nenhuma variável "_nome" neste escopo, ele vai buscar o atributo da classe
_nome = nome;
}
}