Is there a difference between the use of the underscore and the . this?

Asked

Viewed 230 times

1

From what I’ve seen, we use underscore for class internal variables:

class Pessoa {
    private string _nome;

    public Pessoa(string nome){
        _nome = nome;
    }
}

For this case, the use of . this, would be so?

class Pessoa {
    private string nome;

    public Pessoa(string nome){
        this.nome = nome;
    }
}

If yes, there are differences between the two uses?

2 answers

3


Your code is correct

class Pessoa {
private string nome;

public Pessoa(string nome){
    this.nome = nome;
}
}

o . this will always reference the internal class property.

Answering your question about use:

The original orientation for the . NET was never to use underscores unless they were part of a private member variable and then only as a prefix, for example customerId. This was probably inherited from MFC where’m' was used as a prefix for member variables.

The current practice is not to use underscores. Disambiguation between private member variables and parameters with the same name must be done using "This". In fact, all references to private members should be prefixed with 'This'.

Source: https://stackoverflow.com/questions/9782084/naming-conventions-in-c-sharp-underscores

  • Put the reference on that please, that wasn’t you who said it! I just read it.

  • 1

    Thank you for the comment, corrected.

  • 1

    This answer is correct. the other is not completely wrong, but creates confusion and indicates things that are not recommended.

1

this is just a pointer to your class. Through it you can see a listing of the properties and methods available in it.

For the above case, you can write the second example without using this. Although you can use it, it is not required in your code.

If you want to know more about this pointer, see this link: Pointer this

Regarding the use of properties with underscore, it is usually used when creating a property as the example below:

    private string _nome;

    public string Nome
    {
        get { return _nome; }
        set { _nome = value; }
    }

In this example you create a public and a private access property where you do not want to expose your access. By default, private property is written with the underscore.

This type of property is called a complete property and is usually used when you want to execute some code in the get and set actions.

If you want to know more about property types, see the link below.

Types of Properties in C#

Browser other questions tagged

You are not signed in. Login or sign up in order to post.