Search code examples
c#getter-setter

Does this public get set for a private variable make sense?


I am working on a codebase a student with questionable knowledge made, here I am just confused if there is any reasonable intend there or if its just unnecessary... I personally would just use the ShowNewButton field and trash the _showNewBtn, please provide an opinion.

private _showNewBtn;
public bool ShowNewButton
        {
            get => _showNewBtn;
            set
            {
                bbNew.Visibility = value == false ? BarItemVisibility.Never : BarItemVisibility.Always;

                _showNewBtn = value;
            }
        }

Solution

  • I see no reason (in the sample you provided) for the _showNewBtn. You now have 2 markers which contain the visibility state of the button. At some point, this will cause problems if you aren't carefull. Either remove the _showNewBtn completely:

    public bool ShowNewButton
    {
      get => bbNew.Visibility == BarItemVisibility.Always;
      set
      {
        bbNew.Visibility = value == false ? BarItemVisibility.Never : BarItemVisibility.Always;
      }
    }
    

    Or justify the existance of _showNewBtn which makes my remark null and void.