Event registration in C# 2.0

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


Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: