BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Reflection
.NET 1.1+

Reflecting Event Information

The sixth part of the Reflection tutorial continues the description of the reflection of class and structure members. This article examines the reflection of events and the properties of the EventInfo class, which describes them.

Obtaining Event Information

This article continues the investigation of type member reflection that has, so far, looked at the reflection of fields, properties and methods. The process used to obtain information relating to a type's events is very similar so here we will concentrate on some of the key information that can be obtained for an event. You should refer to the earlier articles in the tutorial to learn about reflection of members and the use of binding flags.

We will be using types from the System.Reflection namespace in the sample code so add the following using directive to any C# files:

using System.Reflection;

For the example code, we need a class from which to obtain event information. We will use the following simple type with a single event based upon the EventHandler delegate:

public class EventTest
{
    public event EventHandler MyEvent;
}

EventInfo Class

To retrieve details of a type's events you can use the GetEvent or GetEvents methods of the Type class. Much like the methods that obtain information relating to fields, properties and methods, the GetEvent method retrieves a named, public event when used with a single string parameter. The information is collated in an instance of the EventInfo class. The GetEvents method that accepts no arguments returns an array of EventInfo objects representing all of the type's public events. Non-public members can be reflected with either method by using binding flags.

The following sample shows the use of GetEvent to retrieve the single event from the EventTest class:

Type type = typeof(EventTest);
EventInfo info = type.GetEvent("MyEvent");

Console.WriteLine(info.Name);   // MyEvent

EventInfo Properties

Once you have an EventInfo instance, you can use it to find out more about the event. EventInfo is a subclass of MemberInfo, so has all of the properties provided by the MemberInfo class. In addition, there are several useful properties provided directly. These include:

  • EventHandlerType. Returns an instance of the System.Type class that contains the reflected information for the delegate linked to the event. In the case of our example this is the EventHandler delegate.
  • IsMulticast. Returns a Boolean value that indicates if the event's delegate supports multicasting.
Type type = typeof(EventTest);
EventInfo info = type.GetEvent("MyEvent");

Console.WriteLine(info.EventHandlerType);
Console.WriteLine(info.IsMulticast);

/* OUTPUT
            
System.EventHandler
True
             
*/
15 March 2012