0

So I started my intermediate class on C# on Udemy a couple days ago and the instructor was talking about the 'This' keyword. I understand that it's used to reference variables or such in the class and not in the function but I feel like you could still do without it. Let me give you the examples:

public Customer(int id, string name) 
    : this(id) 
{
    this.Name = name;
}

I feel like the 'this.Name' part is absolutely not necessary because I can just type 'Name = name' The instructor was talking about how sometimes you'll have similar names and it's just to make sure you are referencing the correct variable so you don't accidentally type 'name = Name' or something along the lines of that, I'm sure there's got to be a bigger meaning to the 'this' keyword.

maccettura
  • 10,514
  • 3
  • 28
  • 35
MrSanfrinsisco
  • 79
  • 1
  • 2
  • 10

2 Answers2

2

I agree with you in the above example, this.Name = name is pointless, and in fact most compilers would give you a warning stating that it is not necessary.

The point is not that you can have similar names, but that you can have names exactly the same:

private string name;
public Customer(int id, string name) : this(id) {
        this.name = name;
}

It is valid syntax to have name spelt the exact same way as both a class field and local variable. Local variables are referenced by default and so this exists to reference class variables when there is a local variable with the exact same name. Because otherwise there would be no other way to reference them.

Moffen
  • 1,817
  • 1
  • 14
  • 34
2

The main reason for having a this keyword is to make it possible to reference the instance itself in addition to its fields. Consider the visitor pattern for example:

interface Visitor {
    void Visit(Target target);
}
class Target {
    void Accept(Visitor visitor) {
        visitor.Visit(this); // not just a field but a whole instance
    }
}
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97