Reputation: 13
would there be a way to make it so that tastesGood
can only be redefined within Apple
but can still be referenced by Jim
?
public class Apple {
public bool tastesGood = true;
void ChangeYourMind() {
tastesGood = false;
}
}
public class Jim {
void EatApple() {
if (tastesGood) {
Speak("mmmmm!");
} else {
Speak("Yuck!");
}
}
}
Upvotes: 0
Views: 67
Reputation: 155035
Generally speaking, you shouldn't expose fields from classes. Instead expose the value as a property with a public getter, but a private setter. C# uses a different syntax for properties vs. fields.
public class Apple {
public bool TastesGood { get; private set; } = true;
public void ChangeYourMind()
{
this.TastesGood = false;
}
}
Other tips:
PascalCase
(as opposed to camelCase
) for all public members of classes/structs/interfaces.Upvotes: 3