Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string constant for notify property changed

I am working with some existing code and trying to figure out the advantage (if any) of using a string constant for the name of a property when implementing INotifyPropertyChanged interface.

So for example doing this:

/*
 * Why use this instead of string literal
 * in OnPropertyChanged below??
 */
public const string CustomerIdPropertyName = "CustomerId";

private int _customerId;
public int CustomerId
{
    get
    {
         return _customerId;
    }
    set
    {
         if (_cusomterId != value)
         {
              _customerId = value;
              OnPropertyChanged(CustomerIdPropertyName);
         }
    }
}

Instead of this:

private int _customerId;
public int CustomerId
{
    get
    {
         return _customerId;
    }
    set
    {
         if (_cusomterId != value)
         {
              _customerId = value;
              OnPropertyChanged("CustomerId");
         }
    }
}
like image 761
Jeff Anderson Avatar asked Jan 19 '26 14:01

Jeff Anderson


2 Answers

Both versions are equally prone to typing errors.

If you have a somewhat recent version of .NET, your property changed handler should look like this:

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
  var handler = this.PropertyChanged;
  if (handler != null)
  {
    handler(this, new PropertyChangedEventArgs(propertyName));
  }
}

Then your property looks like this:

private int _customerId;
public int CustomerId
{
    get
    {
         return _customerId;
    }
    set
    {
         if (_cusomterId != value)
         {
              _customerId = value;
              this.OnPropertyChanged();
         }
    }
}

And you don't have any trouble with typing errors.

like image 68
nvoigt Avatar answered Jan 21 '26 07:01

nvoigt


There isn't an advantage compiler wise, since both will end up being a constant value.

I can't imagine a real advantage in using the code like that way. Either ways it is easy to make a typo, and you are not going to reuse that constant for anything, so it is pointless.

I had love to see the new nameof keyword implement in the next version of .NET. Or even better, if possible, use [CallerMemberName] as Marc Gravell suggested.

The use of nameof will be useful when having custom calculated properties (like in WPF for example) that don't have their own getter / setter.

like image 32
Patrick Hofman Avatar answered Jan 21 '26 07:01

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!