Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / Visual Basic 9 (2008)
Article

C# Events: Create class events and use that class

Rate me:
Please Sign up or sign in to vote.
1.69/5 (16 votes)
26 May 2008CPOL2 min read 48.3K   760   28   4
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)
        {
<pre>            //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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Internet
Romania Romania
Pop Adrian-Nicolae

.Net programmer

Skype: popnadrian (don't wory, you cann't spam me!)

Comments and Discussions

 
GeneralShort syntax for wiring an event Pin
Uwe Keim14-Aug-07 0:21
sitebuilderUwe Keim14-Aug-07 0:21 
GeneralRe: Short syntax for wiring an event Pin
infidel7914-Aug-07 4:10
infidel7914-Aug-07 4:10 
GeneralRe: Short syntax for wiring an event Pin
Uwe Keim14-Aug-07 21:59
sitebuilderUwe Keim14-Aug-07 21:59 
GeneralRe: Short syntax for wiring an event Pin
Rafael Nicoletti14-Nov-07 5:41
Rafael Nicoletti14-Nov-07 5:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.