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

1

From what I've seen, underscore is used for internal class variables:

class Pessoa {
    private string _nome;

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

In this case, would the use of .this be that way?

class Pessoa {
    private string nome;

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

If yes, are there differences between the two uses?

    
asked by anonymous 01.10.2017 / 16:11

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 class's internal property.

Answering your question regarding usage:

The original orientation for .NET was to never use underscores unless they were part of a private member variable and then just 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: link

    
01.10.2017 / 16:22
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, please see this link: Pointer this

Regarding the use of properties with underscore, it is usually used when we create a property like the following example:

    private string _nome;

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

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

This property type is called full 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.

Property Types in C #

    
01.10.2017 / 16:58