Method To Set Nested Property Value

247 Views Asked by At

I'm writing a plugin for a piece of software that requires all code to be in a single class (or nested classes)...

What I'm wanting to do is create a method that can handle changes to the nested properties of my _data object and give me a central place to do things like setting a dirty flag so I know to save it later.

Below is some code illustrating my file's structure and at the bottom are two pseudo-methods that hopefully can give you an idea of what I'm trying to accomplish.

public class SomePlugin
{
    private DataObject _data;
    private bool _dataIsDirty = false;

    private class DataObject
    {
        public GeneralSettings Settings { get; set; }
    }

    private class GeneralSettings
    {
        public string SettingOne { get; set; }
        public string SettingTwo { get; set; }
    }

    protected override void Init()
    {
        _data = new DataObject
        {
            Settings = new GeneralSettings
            {
                SettingOne = "Example value one.",
                SettingTwo = "Example value two."
            }
        }
    }

    // These are pseudo-methods illustrating what I'm trying to do.
    private void SetData<t>(T ref instanceProperty, T newValue)
    {
        if (newValue == null) throw new ArgumentNullException("newValue");
        if (instanceProperty == newValue) return;

        instanceProperty = newValue;
        _dataIsDirty = true;
    }

    private void SomeOtherMethod()
    {
        SetData(_data.Settings.SettingOne, "Updated value one.");
    }

}
1

There are 1 best solutions below

0
mjwills On

Consider an approach like:

public class SomePlugin
{
    private DataObject _data;
    private bool _dataIsDirty = false;

    public bool IsDirty => _dataIsDirty || (_data?.IsDirty ?? false);

    private class DataObject
    {
        private bool _dataIsDirty = false;

        public bool IsDirty => _dataIsDirty || (Settings?.IsDirty ?? false);
        public GeneralSettings Settings { get; set; }
    }

    private class GeneralSettings
    {
        public bool IsDirty { get; set; }

        private string _settingOne;

        public string SettingOne
        {
            get { return _settingOne; }
            set
            {
                if (value != _settingOne)
                {
                    IsDirty = true;
                    _settingOne = value;
                }
            }
        }

        public string SettingTwo { get; set; } // Won't mark as dirty
    }
}

Note in particular that SettingOne has logic in its setter to determine whether to set IsDirty or not.