C#: Smaller syntax for event handlers.

Using lambda functions you can shorten your event handlers.

E.g.:

With a normal event hander:

class Test
{
	private Timer timer;

	private void Timer_Elapsed(object sender, ElapsedEventArgs e)
	{
		Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));
	}

       public Test()
	{
		this.timer = new Timer();

		this.timer.Elapsed += new ElapsedEventHandler(this.Timer_Elapsed);

		this.timer.Interval = 100;
		this.timer.Start();
	}
}

With an anonymous function:

class Test
{
	private Timer timer;

        public Test()
	{
		this.timer = new Timer();

		this.timer.Elapsed += delegate(object sender, ElapsedEventArgs e)
					 {
						 Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));
					 };

		this.timer.Interval = 100;
		this.timer.Start();
	}
}

And with an anonymous lamba:

class Test
{
	private Timer timer;

        public Test()
	{
		this.timer = new Timer();

		this.timer.Elapsed += (sender, e) => Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));
		//or you can explicitly type your parameters:
		this.timer.Elapsed += (object sender, ElapsedEventArgs e) => Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));

		this.timer.Interval = 100;
		this.timer.Start();
	}
}

And with a named lamda:

class Test
{
	private ElapsedEventHandler elapsedEventHander;
        private Timer timer;

        public Test()
	{
		this.timer = new Timer();

		this.elapsedEventHander = (sender, e) => Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));

		this.timer.Elapsed += this.elapsedEventHander;

		this.timer.Interval = 100;
		this.timer.Start();
	}
}

Which one to take? The one that suits you and your current application / case!

Sidenote: sorry for the layout, I will fix it ASAP. Fixed 🙂

3 thoughts on “C#: Smaller syntax for event handlers.”

  1. Heb ge weeral van die gekke computer dinges op u site,
    Jeezes:P
    Ik kan er niet aan uit^^
    Maar goed dat gij er nog aan uitkunt!

    x

  2. Which to choose … it all depends.
    In must circumstances, I still favor the first approach. In most of the situations, I still find it much easier to understand, especially when your event-handler logic contains multiple lines of code.

    In some other situations, I use lambda’s or anonymous delegates. However, I only do this when :
    – the code in the eventhandler is short
    – should not be used in any other places.

Comments are closed.