[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use reflection to list a class's events in C#

[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 | BindingFlags.Static); 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); ListViewMakeRow(lvwEvents, info.Name, info.EventHandlerType.Attributes.ToString(), properties); }

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 to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.