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++;
}
}
>Solution :
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.