If you want to avoid the callback solution and the event chain in each class, you have basically 2 solutions.
The first is to turn local variables of type MyClassX into fields, i.e. something like Chris Gessler, but fully following this approach and removing local vars.
public static void main() { MyClass1 obj = new MyClass1(); obj.c2.c3.SomeEvent += obj_SomeEvent; obj.Method1(); } private static void obj_SomeEvent(object sender, EventArgs e) { Console.WriteLine("Some event fired"); } public class MyClass1() { public MyClass2 c2 = new MyClass2(); public void Method1() { c2.Method1(); } } public class MyClass2() { public MyClass3 c3 = new MyClass3(); public void Method1() { c3.Method1(); } } public class MyClass3() { public event EventHandler SomeEvent; private void OnSomeEvent() { if (SomeEvent!= null) { SomeEvent(this, new EventArgs()); } } public void Method1() { OnSomeEvent(); } }
Another option (but it really depends on what you are trying to do, if possible, and I still don't like it) is to simply define the event in MyClass3 as static:
public static void main() { MyClass3.SomeEvent += obj_SomeEvent; MyClass1 obj = new MyClass1(); obj.Method1(); } private static void obj_SomeEvent(object sender, EventArgs e) { Console.WriteLine("Some event fired"); } public class MyClass1() { public void Method1() { MyClass2 obj = new MyClass2(); obj.Method1(); } } public class MyClass2() { public void Method1() { MyClass3 obj = new MyClass3(); obj.Method1(); } } public class MyClass3() { public static event EventHandler SomeEvent; private void OnSomeEvent(MyClass3 anObj) { if (SomeEvent!= null) { SomeEvent(anObj, new EventArgs()); } } public void Method1() { OnSomeEvent(this); } }
Francesco baruchelli
source share