Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I need Keyword "this" in method of the class? in my case?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading