63

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

Sample please as seeing is believing

sameer
  • 1,635
  • 3
  • 23
  • 35

4 Answers4

95

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.

mnme
  • 620
  • 6
  • 19
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Small question: "subscribing instance" refers to the subject or to the observer? It's only one of them that is being rooted? – vandermies Apr 19 '23 at 11:04
11

Yes, you can. See, for example, Application.ApplicationExit. Note, however, the warnings on that page about memory leaks when attaching to static events; that applies to all static events.

There's nothing magical about when you use them: when you need to provide an event for a static class or an event that deals exclusively with static data and it makes sense to implement it this way.

Dave Mateer
  • 17,608
  • 15
  • 96
  • 149
3

Yes, you can declare an event as static. You use them the same way you would use them if they were instance events, but you access the event name in a static way (i.e. ClassName.EventName, rather than variableName.EventName).

Now... do you want static events? That's highly debatable. I personally would say no, since static anything creates difficulties in testing and should thus be avoided whenever possible.

But it's certainly possible.

Randolpho
  • 55,384
  • 17
  • 145
  • 179
0
public delegate void SomeEventDelegate();

public class SomeClass
{
        public static event SomeEventDelegate SomeEvent;
}
sechastain
  • 656
  • 3
  • 5