0

I have the following code (example) that bascially has two classes. I wish is that whenever MyClass's Age property is changed, it triggers MyClass2's method detect.

My problem is I have a lot of MyClass2 in my code and I don't want to initiate an event every time MyClass2 is initiated. Is there a more "clean" way of writing this? Is there a way to let the two classes talk to each other whenever both of them are initiated?

using System;
public class Program
{
    public class MyClass
    {
        private int _age;
        public class AgeEventArgs : EventArgs
        {
            public int Age { get; set; }
        }
        public delegate void AgeChangedHandler(object source, AgeEventArgs e);
        public event AgeChangedHandler AgeChanged;
        protected virtual void OnAgeChanged()
        {
            AgeChanged?.Invoke(this, new AgeEventArgs { Age = _age });
        }
        public int Age
        {
            get { return _age; }
            set
            {
                _age = value;
                OnAgeChanged();
            }
        }
    }

    public class MyClass2
    {
        public void detect()
        {
            Console.WriteLine("b detects it");
        }
    }

    public static void Main()
    {
        var a = new MyClass();
        var b = new MyClass2();
        a.AgeChanged += (o, e) => b.detect(); // I actually don't want to put it here.  
        //Since my code there are a lot of "Class2" it would be very inconvenient to call it                         
        //every time b is initiated
        a.Age = 10;

    }
}
Wiley Ng
  • 113
  • 10
  • you can implement INotifyPropertyChanged. Please check -> https://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist https://stackoverflow.com/questions/1780655/observablecollectiont-in-winforms-and-possible-alternatives https://docs.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-property-change-notification?view=netframeworkdesktop-4.8 https://www.codeproject.com/Questions/5286787/Csharp-write-a-property-change-notifier https://stackoverflow.com/questions/13376328/inotifypropertychanged-notify-another-class – Md. Faisal Habib Apr 17 '22 at 11:34

0 Answers0