Our Character class is public, as are its fields and method. However, what if we wanted a method that can reset a character's data back to its initial values? This could come in handy, but can prove disastrous if it was accidentally called, making it a perfect candidate for a private object member:
- Create a private method, called Reset, with no return value inside the Character class:
- Set the name and exp variables back to "Not assigned" and 0, respectively:
private void Reset()
{
this.name = "Not assigned";
this.exp = 0;
}
- Try and call Reset from LearningCurve after printing out the hero2 data:Â
If you're wondering whether Visual Studio is broken, it's not. Marking a method or variable as private will make it inaccessible using dot notation; if you manually type it in and hover over Reset(), you'll see an Error message regarding the method being protected...