Click here to Skip to main content
15,886,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to design a class where each of the properties of the class is added and updated in an ObservableDictionary.

Here is the code I have come up with.

class Win32_DiskDrive : INotifyPropertyChanged
{
    private readonly string _classname = "Win32_DiskDrive";

    public string ClassName
    {
        get
        {
            return _classname;
        }
    }

    private string _caption;

    public string Caption
    {
        get
        {
            return _caption;
        }

        set
        {
            if ((value != _caption) || (value != null))
            {
                _caption = value;
                UpdateDictionary();
                OnPropertyChange();
            }
        }
    }

    private string _serialNo;

    public string SerialNumber
    {
        get
        {
            return _serialNo;
        }
        set
        {
            if ((value != _serialNo) || (value != null))
            {
                _serialNo = value;
                UpdateDictionary();
                OnPropertyChange();
            }
        }
    }

    private IDictionary<string,string> _diskDriveProperties = new ObservableDictionary<String, String>();

    public IDictionary<string, string> PropertiesDictionary
    {
        get
        {
            return _diskDriveProperties;
        }

        set
        {
            _diskDriveProperties = value;
        }
    }

    private void UpdateDictionary([CallerMemberName] string propertyname = null)
    {
        _diskDriveProperties[propertyname] = this.GetType().GetProperty(propertyname).GetValue(this).ToString();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChange([CallerMemberName] string propertyname = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
    }
}


What I have tried:

My implementation uses reflection to update the Dictionary. Is there a way to implement this class without reflection by using Linq?
Posted
Comments
Tomas Takac 7-Mar-17 2:40am    
You can pass the value into the UpdateDictionary method:
private void UpdateDictionary(string value, [CallerMemberName] string propertyname = null)
{
_diskDriveProperties[propertyname] = value;
}


Then call it like this:
UpdateDictionary(value);
Sabyasachi Mukherjee 7-Mar-17 10:19am    
Thank you. I knew I was missing something simple.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900