Thursday, July 10, 2008

Create an Event for a C Sharp Class

Programming Language: C#
Type: Guide, Tutorial
Level: Moderate
Topic Category: General Programming
Topic Title:
Create an Event for a C Sharp Class - Article I wrote for wikiHow


I found this new Wiki which is also powered by WikiMedia, the same organization that powers Wikipedia. It features a wiki of how-to articles wrote by volunteers, and I can't resist this. So I wrote the following article in wikiHow. It was my first contribution to the site and I hope it will not be the last. I also include it here for those not familiar with wikiHow and for my students. I kept the same article structure used in wikiHow which is designed for good how-to documents and might be not really appropriate for a blog. however, because the site is based on a Creative Commons license, I had to keep the disclaimer at the end. My Screen Name on wikiHow is C#Freak which I'm trying to use in every community from now on.

from wikiHow - The How to Manual That You Can EditMany 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.

Steps

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{ return fieldName;} 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: private EventNameEventArgs(){}
  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:public EventNameEventArgs(string oldValue, string newValue){oldVal = oldValue; newVal = newValue;}

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 EventNameHandler(object sender, EventNameEventArgs e);

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;

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

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 = new EventNameHandler(); 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.
Article provided by wikiHow, a collaborative writing project to build 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. All content on wikiHow can be shared under a Creative Commons license.

No comments: