Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

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

General Tech Learning Aids/Tools
Max. 2000 characters
Replies

usr_profile.png
Pooja Bhardwaj

User

( 6 months 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!

usr_profile.png
Shalini Jaiswal

User

( 6 months 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 ... :)

what's your interest


forum_ban8_5d8c5fd7cf6f7.gif