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

General Tech Learning Aids/Tools 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Learning Aids/Tools related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 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!

profilepic.png
manpreet 2 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.