-1

I study c# from a little bit old book, but it is nice book, here the author use this keyword to modify or call the field of the class but actually even if I delete this keyword from the method it works perfect. when do I need this keyword actually?

Dog dog = new();
System.Console.WriteLine(dog.GetAge());
dog.MakeOlder();
System.Console.WriteLine(dog.GetAge());


class Dog{
    int age = 2;

    // Field Declaration
    public int GetAge(){
        return this.age;
    }
    public void MakeOlder(){
        this.age++;
    }
}
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • [Please try](https://meta.stackoverflow.com/questions/261592) to look for existing answers before posting, for example by [using a search engine](https://duckduckgo.com/?q=c%23+when+do+I+need+this+keyword). – Karl Knechtel Sep 27 '22 at 03:40
  • 1
    this keyword make the semantics clearer – WENJUN CHI Sep 27 '22 at 03:41
  • 1
    question in title seems odd, when you have already figured out, by deleting this, that you don’t need it at all – Rand Random Sep 27 '22 at 03:47

1 Answers1

1

this keyword is used to increase the readability, in your case. Of the other reasons, it can also be used to distinguish another variable, when its shadowing the member variable.

For example:

class Student{
    String name;
    int age;

    public SetStudent(string name, int age){
         this.name = name;
         this.age = age;
    }
}

Here, the parameters passed to SetStudent shadows the member variables. To distinguish between both this keyword is used here. Although its a bad practice to keep the parameter name same as member variable name.

Abhishek Dutt
  • 1,308
  • 7
  • 14
  • 24