Search code examples
c#ref

how can ref multi type same time in c#


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);
        }

    }

Solution

  • 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.