Use reflection to list a class’s events in C#


This example uses the following code to add some simple events to the Form1 class.

// Make some events.
public delegate int MyPublicDelegate(string index);
public event MyPublicDelegate MyPublicEvent;

private delegate int MyPrivateDelegate(string index);
private event MyPrivateDelegate MyPrivateEvent;

public virtual event MyPublicDelegate MyVirtualEvent;

When the program’s form loads, the following code uses reflection to display information about the class’s events.

// List the events.
// Use the class you want to study instead of Form1.
EventInfo[] event_infos = typeof(Form1).GetEvents(
    BindingFlags.FlattenHierarchy |
    BindingFlags.Instance |
    BindingFlags.NonPublic |
    BindingFlags.Public |
foreach (EventInfo info in event_infos)
    string properties = "";
    if (info.EventHandlerType.IsNotPublic)
        properties += " private";
    if (info.EventHandlerType.IsPublic) properties += " public";
    if (info.EventHandlerType.IsSealed) properties += " sealed";

    if (properties.Length > 0)
        properties = properties.Substring(1);

The code gets the Form1 type and calls its GetEvents method to get information about the class’s events. See the example Use reflection to list a class’s properties in C# for information about the BindingFlags parameters.

The code then loops through the EventInfo objects that GetEvents returns. The code checks a series of EventInfo properties to get information about the field’s accessibility and builds a string describing the values.

The code finishes by calling the ListViewMakeRow method to display the information in the form’s ListView control. The EventInfo object’s Name property gives the method’s name. The EventHandlerType.Attributes property returns information about the event’s attributes.

Download the example program to see how the ListViewMakeRow method works and for other details.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in reflection and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.