Create an Event for a C Sharp Class

This article was provided by wikiHow, a wiki building the world's largest, highest quality how-to manual. Please edit this article and find author credits at the original wikiHow article on how to create an event for a c sharp class. Content on wikiHow can be shared under a Creative Commons License.

Grade B Views 432
Last edited 2 months ago

Many C# programmers use events in other classes by attaching event handlers to them but have you ever wanted to implement your own event(s) in classes that you develop? This is a systematic straightforward guide to creating your own events without worrying about forgetting anything.

Step 1  

Create the Event Arguments Class:  

  1. Decide what you want to communicate with your event subscribers (other programmers who will attach event handlers to your event). For example, if your event is to notify developers when a value changes, you might want to tell them the old value and the new one. If you have nothing to communicate to subscribers, use the System.EventArgs class and skip this step.
  2. Create a class named EventNameEventArgs where EventName is the name of your event
  3. Inherit the EventNameEventArgs class from System.EventArgs
  4. Create a protected field for each piece of data you want to communicate with your subscribers. For example, in an event that will notify developers of a change in a string value, you might want to tell them the old and the new strings so the fields will look like: protected string oldVal, newVal;
  5. Create a public property for each field you created in 1.4 that has only a get{ returnfieldName;} method (where fieldName is the name of the field you created in 1.4
  6. Create a private empty constructor for the class with no implementation. The constructor should look like: privateEventNameEventArgs(){}
  7. Create a public constructor for the class that takes as many arguments as there is fields/data. For example, in a string value change event, the constructor will look like: publicEventNameEventArgs(string oldValue, string newValue){oldVal = oldValue; newVal = newValue;}

Step 2  

Declare the event delegate. If you did not create an event arguments class because there is no data to communicate with subscribers, use the System.EventHandler delegate and skip this step. The delegate declaration should look like: public delegate void EventName Handler(object sender, EventNameEventArgs e);

Step 3  

Declare the event itself in the containing class: use the event handler delegate you declared/decided in 2 as the event type. The declaration should look like: public event EventNameHandler EventName;

Step 4  

Declare the event-firing method - a protected virtual method that has exactly the following declaration: protected virtual void On EventName (EventNameEventArgs e){ if (EventName  != null) { EventName (this, e); } } Use the event arguments class you decided to use in 1

Step 5  

Call the event-firing method you declared in 4 whenever the event occurs. This is the hardest part. You should know when the event you are creating will fire (what areas in your code causes the event to occur) and call the method with the appropriate event arguments class instance. For example, in the string value change event, you must see what code can cause this value to change, save its old value before the change, allow the code to change the value, create an event arguments object with the old and new values passed to the constructor and pass the object to the event-firing method.

Tips

  • Be committed to the naming convention stated in this guide, it is a de-facto standard and most .NET/Mono developers use it.
  • Do not over communicate to your subscribers. In other words, do not transfer data that is not related to the event.
  • Choose the name of your event carefully and clearly. Event names like "ValPsd" instead of "ValuePassed" is not encouraged.
  • Usually, the accessibilities used in this article is the case. However, you can change the accessibility of any declaration as long as it does not render the element changed unusable by other elements of the event creation process.
  • Examine all places in your code where the event might occur. Sometimes, more than one piece of code causes the event to fire.
  • Watch for any changes you make to your class after you declare the event. See if the change affects the triggering/firing of the event.

Warnings

  • If you are adding the event to a struct instead of a class, take notice of the following changes:
    1. Use "private" instead of "protected virtual" when declaring the event-firing method in 4.
    2. In the constructor of the struct that declares the event, you must initialize the event itself or you will get a compile error. Initialize events by creating new event handler delegate objects and assigning them to the event. The initialization code should look like: EventName = newEventNameHandler(); or EventNameHandler = null;

Things You'll Need

  • A .NET framework installed (either MS .NET framework on Windows or Mono on other operating systems).
  • A C# compiler (the csc tool in the MS .NET SDK, cmcs in the Mono framework, or the compiler included in .NET IDEs such as Visual Studio 2005/2008 for Windows or MonoDev for Linux).
  • The code of the class you wish to add the event to.
  • Some code editing tool (Notepad is enough, but Visual Studio, MonoDev, Notepad++ or any other editor might make development and code writing easier).

Via wikihow

Ew. Livestream of Patient's Brain Being Sliced. Watch Now.

Neuroscience (live!) resumes its 50 hour slicing session 8:00 am PST this morning. According to Gizmodo, "Studying Henry Gustav Molaison, more commonly known as Patient H.M., and his memory ...

Pyro-Spirograph-Drawings

Rosemarie Fiore is badass. She makes art with pyrotechnics, amusement park rides, Atari, guns, and pinball machines. Though all of her work is cool, I have to say my favorite piece is Fiore's larger ...

Who Needs Jump Rope When You Have a Flexible Friend

Breakdancing. Acrobatics. Gymnastics. Human jump roping fits in all. And why not? It's frickin' awesome. (Image credit: Flickr user envycleopatra.)

Indian Spiderman Defies Gravity (and Death)

Real life spiderman, Jyothi Rai of India, spends his time entertaining tourists by scaling walls of the Chitradurga Fort. The daredevil works completely harness free. Inspired? WonderHowTo's Climbing ...

Creepy Crawler Ant Robot

Wow, this robot has incredible movement. "A-Pod is an ant inspired hexapod robot with a 2 DOF abdomen (tail), a 3 DOF head with large mandibles. 6 legs with 3 DOF each. Total 25 servos ...

loading...