Click here to Skip to main content
11,705,453 members (32,303 online)
Click here to Skip to main content
Add your own
alternative version

Events and Delegates Simplified

, 28 Nov 2012 CPOL 1.3M 13.8K 582
This article shows you how to design events for your classes.
events_demo.zip
events_demo
Events.exe
events_src.zip
Events.csproj.user
App.ico
using System;

namespace Events
{
	public delegate void NumberReachedEventHandler(object sender, NumberReachedEventArgs e);

	/// <summary>
	/// Summary description for Counter.
	/// </summary>
	public class Counter
	{
		public event NumberReachedEventHandler NumberReached;
		
		public Counter()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		public void CountTo(int countTo, int reachableNum)
		{
			if(countTo < reachableNum)
				throw new ArgumentException("reachableNum should be less than countTo");
			for(int ctr=0;ctr<=countTo;ctr++)
			{
				if(ctr == reachableNum)
				{
					NumberReachedEventArgs e = new NumberReachedEventArgs(reachableNum);
					OnNumberReached(e);
					return;//don't count any more
				}
			}
		}

		protected virtual void OnNumberReached(NumberReachedEventArgs e)
		{
			if(NumberReached!=null)
			{
				NumberReached(this, e);
			}
		}
	}

	public class NumberReachedEventArgs : EventArgs
	{
		private int _reached;
		public NumberReachedEventArgs(int num)
		{
			this._reached = num;
		}
		public int ReachedNumber
		{
			get
			{
				return _reached;
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Meysam Mahfouzi
Software Developer (Senior)
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
My main focus is currently on C++, but I have enjoyed developing with C# too Smile | :)

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150819.1 | Last Updated 29 Nov 2012
Article Copyright 2003 by Meysam Mahfouzi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid