There might be times when you'll want your event to perform the same actions for all objects. One way to do that is to add a same event handler to the event for each object separately, but the easier (lazier) way is to simply create a static event,
- using System;
-
-
-
- delegate void MyEventHandler(object sender);
-
- class MyClass
- {
-
- public static event MyEventHandler MyEvent;
-
-
- public void EventInvokingCode(int num)
- {
-
-
- if (num % 2 == 1 && MyEvent != null)
- {
-
- MyEvent(this);
- }
- }
-
-
-
- public string Name { get; set; }
- }
-
- class main
- {
- static void onEvent1(object sender)
- {
- string objName = ((MyClass)sender).Name;
- Console.WriteLine("Object's name: " + objName);
- }
-
- static void onEvent2(object sender)
- {
- string objName = ((MyClass)sender).Name.ToLower();
- Console.WriteLine("Object's name: " + objName);
- }
-
- static void Main()
- {
-
- MyClass obj1 = new MyClass();
- obj1.Name = "C SHARP IS";
- MyClass obj2 = new MyClass();
- obj2.Name = "NOT";
- MyClass obj3 = new MyClass();
- obj3.Name = "GREAT";
- MyClass obj4 = new MyClass();
- obj4.Name = "MONKEY BUSSINES";
-
-
- MyClass.MyEvent += onEvent1;
-
-
-
- MyClass.MyEvent += (object sender) =>
- {
- int lenght = ((MyClass)sender).Name.Length;
- Console.WriteLine("*name len: " + lenght);
- };
-
-
- obj1.EventInvokingCode(1);
- obj2.EventInvokingCode(4);
- obj3.EventInvokingCode(3);
- obj4.EventInvokingCode(8);
-
-
-
-
- MyClass.MyEvent -= onEvent1;
- MyClass.MyEvent += onEvent2;
-
-
- Console.WriteLine("\n\nAnother run:\n");
- obj1.EventInvokingCode(5);
- obj2.EventInvokingCode(7);
- obj3.EventInvokingCode(2);
- obj4.EventInvokingCode(9);
- }
- }
The program produces the following output,
Object's name: C SHARP IS
*name len: 10
Object's name: GREAT
*name len: 5
Another run:
*name len: 10
Object's name: c sharp is
*name len: 3
Object's name: not
*name len: 15
Object's name: monkey bussines
|
Notice that in the second run the event handler displaying the length of object's name is executed first. This is because we added that handler before the new one.
Unfortunately there is no simple way to remove an anonymous method from a collection of added handlers. We can remove all handlers with a foreach loop, but if we want to remove only a specific anonymous method, we have to keep a track of its index in the collection. We can get the collection by using Delegate.GetInvocationList method.
Static event would be useful, if, for example, you had a list of items and you'd want them to invoke some actions when a certain condition is reached or change is made. This could all still be done with a simple function call, but it's better to add and remove actions in a form of events than to run through a set of conditional statements on each call.
Thanks for reading!