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