Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C# Events: Create class events and use that class

0.00/5 (No votes)
26 May 2008 1  
Educational article about C# events

Introduction

Learn to create Events and to use that event in C#.

Background

The source code presented here comes from Visual Studio 2005. If you use other environment you have to parse the solution to your environment. See the web for that !!!

Using the code

The code is the most important part for an programmer. Download it, watch it and after that back here, if you are not 100% ensured by that.

First you have to see my classes, the class with the event and the :

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace learnEvents
{
    public delegate void WorkerEndHandler(object o, WFEventArg e);

    /// <summary>
    /// EventArg -> necesary to do corect your job
    /// </summary>
    class WFEventArg : EventArgs
    {
        public readonly string TheString;

        public WFEventArg(string s)
        {
            TheString = s;
        }
    }

    /// <summary>
    /// The class with the event
    /// </summary>
    class Worker
    {
        public readonly string Name;
        public event WorkerEndHandler WorkEnd;

        public Worker(string name)
        {
            Name = name;
        }
        public void Work(string s)
        {
            Thread.Sleep(2500);//Sleep, thats our job :)
            
            //Create a new event arg and after that...
            WFEventArg e1 = new WFEventArg(s);
            //...release it
            OnWorkEnd((object)this, e1);
        }

        void OnWorkEnd(object o, WFEventArg e)
        {
            //release the object
            if (WorkEnd != null)
                WorkEnd(o, e);
        }
    }
} 

What's happen there ... We create a simple class named Worker, class that contain an procedure named Work, procedure with an parameter (an string); this function is not doing nothing, just sleep for 2.5 seconds and after that release an event (tell to <somebody> that it finish it's job). For that we need an delegate -WorkerEndHandler- and a class named WFEventArg, class who inherits the class EventArgs. The event is released by the method called OnWorkEnd

After that we have to use that event ... well, I create a simple form with two buttons and an label and I create two objects Worker (wkr1, wkr2). When you click the first button the first worker (wkr1) will work and so on with the second button. When the form is loaded we tell to our workers what to do when they finish their jobs -> we use the Event. The events of our workers are in the same method: wkr_WorkEnd. The params of this function are the same like the params of the method who release the event OnWorkEnd and you can customize this params, by your needs. In the end, this method do what we wont to do at that event: I set the label text field with the EventArg class and I tell to the user that the worker finished his job. You can do what you want at this event, you are free to chose!

The code of the form is here:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace learnEvents
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region Lesson
        //we create two workers -> see that class
        Worker wkr1 = new Worker("The 1'st worker");
        Worker wkr2 = new Worker("The 2'nd worker");

        private void button1_Click(object sender, EventArgs e)
        {
            //We tell him to work...
            wkr1.Work("AnAbAnAnA");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //We tell him to work...
            wkr2.Work("aNaBaNaNa");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //We spent two events ....
            wkr1.WorkEnd += new WorkerEndHandler(wkr_WorkEnd); 
        /*is similar with <<wkr1.WorkEnd += wkr_WorkEnd;>> 
        but if you use VS 2005, it's utilities will help you to build the 
        function with who will treat this event. I don't know if there are
        more benefits for writing this short syntax for wiring this event 
        */

        wkr2.WorkEnd += new WorkerEndHandler(wkr_WorkEnd);
            ///...with the same function! 
        }

        void wkr_WorkEnd(object o, WFEventArg e)
        {
            //The results ...
            Worker worker = (Worker)o;

            label1.Text = e.TheString;
            MessageBox.Show(worker.Name + ":\tI've done my job!!!");
            //...is different from an object to another!
        }
        #endregion
    }
} 

Points of Interest

The events are necessary in c# programing, in all domains: desktop applications, web applications, console applications and so on!

History

There are many articles at this theme but i submit this article thinking that who wants to learn to use events, can learn very easy when he has an simple project like an example.

Good luck to everybody!

ads by me

http://iuliumaniu.ro/

http://floridecrin.iuliumaniu.ro/

http://the-search-engine.blogspot.com/

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here