Click here to Skip to main content
12,623,027 members (29,411 online)
Click here to Skip to main content

Stats

1.4M views
15.9K downloads
604 bookmarked
Posted

Events and Delegates Simplified

, 29 Nov 2012 CPOL
This article shows you how to design events for your classes.
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)
No Biography provided

You may also be interested in...

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