Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping the property setter

I find that I'm repeating myself alot and that is of course no good. So I wondered if I could do something about it. This is a common code in my WPF application:

private string _name;
public string Name
{
    get { return _name; }
    set
    {
        if (_name != value)
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }
}

So I was wondering if I could wrap the setter somehow to make it better and more readable. One idea was something like this:

protected void PropertySetter<T>(T property, T value, string name)
{
    if (EqualityComparer<T>.Default.Equals(property, value))
    {
        property = value;
        OnPropertyChanged(name);
    }
}

Usage like this:

private string _name2;
public string Name2
{
    get { return _name2; }
    set
    {
        PropertySetter<string>(Name2, value, "Name2");
    }
}

But I'm not sure this is really smart or would work as well with Value types?

I guess I'm not the first one to try something like this so if someone knows a good foolproof way to something like this please chime in. I guess I couldn't make the propertyChanged typesafe without reflection but any ideas there would also help.

like image 663
Ingó Vals Avatar asked Jun 18 '12 15:06

Ingó Vals


1 Answers

Yes - this is completely acceptable and normal code.

Here's an example I found that's pretty standardized (I see a lot of this type of usage in code samples).

public event PropertyChangedEventHandler PropertyChanged;

private void SetProperty<T>(ref T field, T value, string name)
{
    if (!EqualityComparer<T>.Default.Equals(field, value))
    {
        field = value;
        var handler = PropertyChanged;
        if (handler != null)
        {
          handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

Wrap this code inside of a class that implements INotifyPropertyChanged, and inherit your data objects from this class.

In your example, you are calling the event directly - never do this. You could lose the event reference from the time the method starts to the time you call the event. Always create a local cache of the event before invoking it.

like image 158
qJake Avatar answered Sep 28 '22 09:09

qJake