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

Philipp Räse
PLUS
Philipp Räse
Courses Plus Student 10,073 Points

Using different getter/setter appearance. Just a question of style or has it a relevant influence?

I could use my getter and setter methods in 2 special kinds.

1: Defining explicit getter/setter Methods

class Invader
{
  // Defining my variable
  private MapLocation _location;

  // public getter-Method()
  public MapLocation GetLocation()
  {
    return _location;
  }

  // public setter-Method()
  public void SetLocation(MapLocation value)
  {
    _location = value;
  }
}

2: Defining a public variable that points with its getter/setter to my private variable

class Invader
{
  // Defining my variable
  private MapLocation _location;

  // public accessable variable including its getter/setter
  public MapLocation Location
  {
    get
    {
      return _location;
    }
    set
    {
      _location = value;
    }
  }
}

Is there any functional difference between these to ways to use getter/setter? Or is that just a matter of personal preference?

1 Answer

Philipp Räse
PLUS
Philipp Räse
Courses Plus Student 10,073 Points

Okay, the answer followed in the next video... ;-)

Question solved by Treehouse already!