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 trialRanvir Sahota
9,844 Pointspublic MapLocation Location => path.GetLocation(pathStep); How does it know to get?
The question is in the title. How do expression bodies members know the statement is for, get not set? Can you do the same for set? Please provide an example if it can be done. How does the compiler know path.GetLocation(pathStep) is to be returned?
2 Answers
luke hammer
25,513 PointsHe covers this quickly at
timestamp 1:40 "Location is still a property. The Location property reduces to just calling _path.GetLocationAt. So long as this part on the right side evaluates to a MapLocation, and you can write it in a single statement, then you can write it like this."
So i think the key to take away is what is returned by the function you are calling. Get method return the item that you are getting.
However the Set method normally returns void. This cue of what is being returned is what the compiler can see. I'm not aware of away to assume a setter. (i think that would make code very hard to read.
but here is an example of adding a setter to that line
public MapLocation Location { get => _path.GetLocationAt(_pathStep); set => Location = value ; }
luke hammer
25,513 PointsMy rule of thumb is that if the whole line
public MapLocation Location { get => _path.GetLocationAt(_pathStep); set => Location = value ; }
Does not fit on a single line then use a more traditional setter or getter.
but in my experience, if your get or set is so long you can not declare it on a single line There is a good change you need to abstract to a different method or function anyway.
This code is a good example of this.
with it using a _path.GetLocationAt() function.
Ranvir Sahota
9,844 PointsRanvir Sahota
9,844 PointsSo basically there is no shorthand for set. And get always returns something when set doesn't, otherwise they wont getters and setters. Thanks
drstrangequark
8,273 Pointsdrstrangequark
8,273 PointsSo basically, this shorthand is only useful in relatively simple instances, correct? If you need to add additional code to "get" or "set" you should write it out longhand?