How to create and listen for static events in c# — by Steven Lacerda (Morgan Hill, CA)

Steven Lacerda
2 min readAug 15, 2018

--

If you’re planning on firing the event from a static method, or class, then you should make your event static. Here’s an example,

In my account.cs file:

class Account{  public delegate void OnDeleteEventHandler(string id, string siteId);  public static event OnDeleteEventHandler OnDelete;  public static void Delete(string id, siteId)  {    // your regular code here    // then check to see if any of your code is 
//listening here, by checking subscribers to the event
if (OnDelete != null) { // fire the event OnDelete(id, siteId); } }}

Then in my other file, let’s call this chatservice.cs:

public class ChatService{  // in my constructor, when the instance is created, 
// I create a listener that's attached to the delegate
public ChatService() { Account.OnDelete += (id, siteId) => UserDeleted(id, siteId); } public UserDeleted(string id, string siteId) { // do something with event here }}

Voila, that’s all there is to it.

This is by far the best way to keep your code isolated. Imagine, now when OnDelete fires, you could have threads running all over the place, all without having to call the code directly from the Delete method. So, that means account.cs doesn’t rely on any of the other classes in order for it to do it’s job, it just fires the event and chatservice listens.

Don’t be a prisoner to your code, master it!

Solving a problem is as good as those sexual feelings…sometimes, okay, maybe not. Straight from Morgan Hill, CA. Good luck!

By Steven Lacerda

— by Steven Lacerda

--

--

Steven Lacerda
Steven Lacerda

Written by Steven Lacerda

Steve Lacerda is a software engineer specializing in web development. His favorite 80’s song is Let’s Put the X in Sex by Kiss.

No responses yet