Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Events be declared as Static, if yes how and why

Tags:

c#

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

like image 348
sameer Avatar asked May 07 '10 14:05

sameer


People also ask

What does static event mean?

With a static event, there is no sending instance (just a type, which may or may not be a class). There still can be a recipient instance encoded as the target of the delegate.

How do you declare an event variable in C#?

Use "event" keyword with delegate type variable to declare an event. Use built-in delegate EventHandler or EventHandler<TEventArgs> for common events. The publisher class raises an event, and the subscriber class registers for an event and provides the event-handler method.

What are events in C# with example?

Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts.

Why do we need events in C#?

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.


2 Answers

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.

like image 157
Reed Copsey Avatar answered Oct 23 '22 02:10

Reed Copsey


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.

like image 41
Dave Mateer Avatar answered Oct 23 '22 02:10

Dave Mateer