2

please could you explain me what is the difference between this two implementation of constructors:

 public User(string a, string b)

    {

        name = a;

        location = b;

    }

and this one:

  public User(string a, string b)

    {

        this.name = a;

        this.location = b;

    }

From the compiler point of view I don't see any difference. Please explain it.

Heron
  • 329
  • 2
  • 5
  • 15
  • 1
    There is no difference. However, if the parameter name happened to be the same as the field or property name being assigned, you would *have* to use `this.` to disambiguate the assignment. – Matthew Watson Oct 27 '18 at 08:48
  • https://stackoverflow.com/a/33187034/2946329 – Salah Akbari Oct 27 '18 at 08:51
  • Possible duplicate of [What is the meaning of "this" in C#](https://stackoverflow.com/questions/6270774/what-is-the-meaning-of-this-in-c-sharp) – Anas Alweish Oct 27 '18 at 08:52

1 Answers1

3

There is no difference,

this just references the class, its useful if the parameters you pass in have the same name as the fields in your class (to differentiate from them)

public class Employee
{
    private string alias;
    private string name;

    public Employee(string name, string alias)
    {
        // Use this to qualify the members of the class 
        // instead of the constructor parameters.
        this.name = name;
        this.alias = alias;
    }
}

Additional Resources

this (C# Reference)

The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • Is it good practice to use also 'this' to the different variable and constructor parameteres or if they are only the same? – Heron Oct 27 '18 at 09:05
  • 1
    @Heron i dont use `this` in that case, some people like it as it stands out, it depends how you like to write your code, someone people like private field names to start with underscore . ie `_field` some dont, if it helps you, then just be consistent, personally, i use underscore for field names , they stick out – TheGeneral Oct 27 '18 at 09:07