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 trialWilliam Schultz
2,926 PointsWhy have the private setter at all?
So I understand using the property to change the health rather than allowing direct access via setter, but what I don't understand is after we created the method DecreaseHealth to reduce the health, why did we change the setter to private instead of just removing the set all together? We don't want any other objects to be able to set the health, so why have it at all? Couldn't we just change the property to be:
public int Health { get; } = 2;
2 Answers
Kyle Southerland
UX Design Techdegree Student 11,117 PointsI'm not the greatest at explaining things, but I'll give this a go. The setter is being set to private because it still needs to be there to set the value, but the access modifier forces others to use DecreaseHealth and prevents direct access to Health. I'm not familiar with the error workspaces would give you, but I believe an IDE like Visual Studio would tell you that you are missing the setter when attempting to change the value if you remove set.
William Schultz
2,926 PointsThanks for the response! That makes sense. I tried it and of course it gave an error indicating that Health could not be set as it is read-only. It makes sense now. Thanks again.