twistedstriker1234
twistedstriker1234

Reputation: 13

C#: Is there a way to make a field of one instance readonly when referenced by other instances of any class?

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

Answers (1)

Dai
Dai

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:

  • In .NET the standard naming convention is to always use PascalCase (as opposed to camelCase) for all public members of classes/structs/interfaces.
  • The example you posted is of an object-oriented class with mutable state - which is fine as I assume you're getting familiar with programming or C#, but I'll advise you that the programming field over the past decade or so is trending towards immutable state and adopting more functional-programming approaches, so keep your eyes open for any articles about FP as you'll learn better when you're still young and malleable.

Upvotes: 3

Related Questions