Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid setting field values directly so to always trigger a setter, and PropertyChanged notifications

I have a class which implements INotifyPropertyChanged. I have a property setter which triggers notification. But the C# compiler does not know/complain anything if I just use the field, and directly assign values. But if I do that property changed notification is completely useless. I am seeing this mistake being made quite often. SO my questions are

  1. How to verify if this mistake (setting filed value instead of using setter) is made in a large solution,
  2. How to force some kind of warning or errors when this happens

Since no question is complete without a code sample, here is the illustration of proplem

class Person : INotifyPropertyChanged
{
        private string personName;
        public string PersonName
        {
            get { return personName; }
            set { if(personName!=value)
                  {
                        personName = value;
                        this.OnPropertyChanged ("PersonName");
                  }
                }
        }
        public bool dummy()
        {
            personName = "not notified"; //need to detect/avoid this
        }
}
like image 488
Adarsha Avatar asked Jan 02 '26 00:01

Adarsha


1 Answers

Maybe you can try an extension.

Kind Of Magic automatically adds at compile time the necessary "raisers" for you. So you can use only Auto-Implemented Properties and avoid the private field.

It works like this:

Instead of write all code:

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

Just use an attribute to do this work:

[Magic] 
public string Name { get; set; }

The extension have much more option. I think you should take a look.

Edit If you search more you can find even more extension that try avoid type all the pattern of INotifyPropertyChanged without lose functionality.

like image 101
Vitor Canova Avatar answered Jan 03 '26 14:01

Vitor Canova



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!