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 🙂

CodeRush Express – Useful tool for C# developers in VS.NET 2K8

(I quote):

Developer Express and Microsoft are proud to announce a new version of CodeRush licensed exclusively for C# developers working in Visual Studio. The new product is called CodeRush Xpress, and it includes a fresh selection of hand-picked features taken from CodeRush and Refactor! Pro.

And I love it! It has very handy functions for refactoring your code very fast!

I recommend it for everyone!

Usefull links (both contain the downloads):

If you are interested in learning the features you can access these movies:

Dustin Campbell also presented a video on this tool, among other useful Visual Studio 2008 shortcuts  on PDC 2008, you can find it here (click below for wmv-hd download).