Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Encapsulation with Properties Accessor Methods

i dont understand the getter here why does it have to return and where is it returning ?

the accessor methods video in c# objects i do not understand he point of a getter here ? why and where does it return

1 Answer

William Ruiz
William Ruiz
10,027 Points

In this video we built how we manage state for an Invader. We are returning _location because, in the future, we will want to know where the invader is located on the grid, relative to where our cannons and our fortress door is located (i.e. have they succeeded, when we shoot at them is it a "hit" or a "miss"). I'm not sure if your broader question is, why do we need to get/set using this pattern at all? Because encapsulation. Jeremy mentions in the video that we could perform additional if/else checks inside the setter, for example, and we might also do additional work inside the getter, if we wanted to for a more complex application. So this pattern protects our private _location from becoming public (and thus prone to being abused by other parts of the code), and it gives us the future flexibility of doing additional work inside the get/set methods if we ever want to.