Michael Olivero
The official blog of Michael Olivero, Software Architect & Humble Entrepreneur

Event registration in C# 2.0

Friday, 26 September 2008 20:11 by Michael Olivero
The C# 2.0 (and newer) compiler is smart enough to determine the type of delegate with which a particular event is implemented. This "delegate inference" capability enables you to omit the declaration of the requisite delegate in the code that registers an event handling method with an event. Consider the following 1.x code that registers an event handling method with an event. This code explicitly instantiates the event handler (delegate) in order to register the associated method with the event.
thePublisher.EventName += new MyEventHandlerDelegate(EventHandlingMethodName);
The following 2.0+ code uses delegate inference to register the same method with the event. Notice the following code appears to register the event handling method directly with the event.
thePublisher.EventName += EventHandlingMethodName;
When you assign the method name directly to the event like that, the C# compiler ensures that the method signature matches the signature of the event handler upon which the event is based. The C# compiler then inserts the requisite delegate registration code (i.e., ... += new MyEventHandlerDelegate(EventHandlingMethodName);) in the output assembly. This simplified syntax is made possible by the C# compiler, and not by any change to the fundamental ways that events are implemented in the .NET Framework. To be clear, it is not the case that events in C# 2.0 (and newer) can directly reference methods. What the compiler is doing for us is supplying the [still] requisite delegate syntax in the output assembly — as if we had explicitly instantiated the delegate. Clipped from: http://www.codeproject.com/KB/cs/event_fundamentals.aspx
Categories:   Software
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed