Using “this” in getters/setters in C# [closed]

General Tech Learning Aids/Tools 3 years ago

6.47K 2 0 0 0

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 years ago

 

Short and sweet (hopefully), is there a specific reason not to use the this keyword when writing getters and setters in C#? I know the typical format, and the one I've always used, is:

    public void SetDay(int _day) { day = _day; }
    public int GetDay()
    {
        return day;
    }

Recently though, I've been learning Java, and in several of the books I've been using I've seen it written instead like this:

    public void SetDay(int _day) { this.day = _day; }
    public int GetDay()
    {
        return this.day;
    }

So basically, is there a reason to avoid doing it the same way in C#? Will it cause any problems or errors, or is it a valid approach and really just a matter of personal preference. I'm wondering because, while I know the this in C# is understood, explicitly using the this keyword seems like it would aid in eliminating a bit extra ambiguity, which personally is always a good thing.

Thank you!

0 views
0 shares

profilepic.png
manpreet 3 years ago

There's not much to it really. You can do it, and you can avoid it. I think it's quite obvious when you're in the getter/setter that you're talking about the object you're in, so I've never used it there.

Also, it seems like Resharper will suggest it's redundant, and gray it out.

If you find it to be of use for you (readability wise), by all means, use it. Otherwise, it'll save you five keystrokes (about a second?) every time you implement a getter by hand ... :)


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Similar Forum