Search code examples
c#events

Can Events be declared as Static?


I want to know if we can declare events as static and if so, why and the application of such declaration.

Sample please as seeing is believing.


Solution

  • You can create static events. You use them the same way as a normal event, except that it's used in a static context within the class.

    public class MyClass
    {
        public static event EventHandler MyEvent;
        private static void RaiseEvent()
        {
            MyEvent?.Invoke(typeof(MyClass), EventArgs.Empty);
        }
    }
    

    That being said, there are many issues with static events. You must take extra care to unsubscribe your objects from static events, since a subscription to a static event will root your subscribing instance, and prevent the garbage collector from ever collecting it.

    Also, I've found that most cases where I'd want to make static events, I tend to learn towards using a standard event on a Singleton instead. This handles the same scenarios as a static event, but is (IMO) more obvious that you're subscribing to a "global" level instance.