2

When I have some object with boolean state that can be changed (like a checkbox's checkedness), there are several ways I can expose it.

  1. Getter property, Setter method

    bool IsChecked { get { ... } }
    void SetChecked(bool checked) { ... }
    
  2. Getter property, Set true method, Set false method

    bool IsChecked { get { ... } }
    void Check() { ... }
    void Uncheck() { ... }
    
  3. Getter, setter property

    bool IsChecked { get { ... } set { ... } }  
    

Is there a good design or logical reason to use one of these ways in particular? (I apologize if this question is too opinion-based/open-ended)

7

Idiomatic C# generally favours properties over accessor methods for simple properties, so just use a property unless there is a good reason not to. If there is complex logic in the getter or setter, it may be better to use accessors to avoid breaking the Principle of Least Surprise.

For a canonical example, WPF checkboxes use a property - although a bool? to include the "partially checked" state.

2

Getter/setter properties are the way to go. They are very clear, code-wise, and don't involve adding a weird smell to an entire codebase. Also, tools like Entity Framework use getter/setter pairs to do work, so a property should be more discoverable by tools, IDEs, and frameworks than any hand-rolled solution.

Generally, if you find yourself wanting to improve on the design of very simple operations, like setting variables or looping, resist! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.