Click here to Skip to main content
15,885,214 members
Articles / Programming Languages / C#

Events and Delegates Simplified

Rate me:
Please Sign up or sign in to vote.
4.89/5 (681 votes)
28 Nov 2012CPOL7 min read 1M   18.4K   625  
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)


Written By
Software Developer (Senior)
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions