-1

I created a master class to be inherited In the rest of the classes Added update alert method and at the same time set value for the property variable The problem is that I have to add a method for each type Is there a way to send the variable? without caring about the type via ref

 public class  mainclass : INotifyPropertyChanged
    {
       
           
        public event PropertyChangedEventHandler PropertyChanged;
       
        public  void NotifyPropertyChange(ref int prop, int value, [CallerMemberName] String propertyName = "")
        {
          if (prop!=value)
            {
                prop = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }

        }

        public void NotifyPropertyChange(ref string prop, string value, [CallerMemberName] String propertyName = "")
        {
          if (prop != value)
            {
                prop = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

  public class testclass: mainclass
    {
        private int myVar;

        public int MyProperty
        {
            get { return myVar; }
            set => NotifyPropertyChange(ref myVar, value);
        }

    }
  • What is wrong with protected void OnPropertyChanged([CallerMemberName] string name = null) ? – Serge Aug 04 '21 at 13:58
  • @Serge the problem is that it makes each setter minimum two lines, and more if you want to compare the new value with the previous. This pattern allow single-line setters. Not a huge deal, but it can add up if you have many properties. – JonasH Aug 04 '21 at 14:01

1 Answers1

3

Just make a generic method:


private void Set<T>(ref T field, T value, [CallerMemberName] string caller = "")
        {
            if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                field = value;
                OnPropertyChanged(caller);
            }
        }

Note that it can be problematic to inherit such a base class since .net only allow single inheritance. I usually just copy such a method to ViewModels that need it.

JonasH
  • 28,608
  • 2
  • 10
  • 23