Sunday, July 24, 2011

C#: Events, Delegates and Action<T>

 

We have all seen and used the code below to hook an event with it’s event handler. It’s quite standard and has existed since the old days of .NET1


This can be re-written using the delegate keyword and eliminating the private method used to handle the event. All the functionality is grouped together in one place, making it easier to read.2


We can eliminate the delegate keyword and the type for the arguments and re-write the above code as shown below using lambda operator. This makes the code more compact and the .NET compiler is smart enough to interpret the code.3