Note that there are some explanatory texts on larger screens.

plurals
  1. POCheck if a given event is subscribed, during runtime, using reflection
    primarykey
    data
    text
    <p>Consider a class that has some events. This event list is going to grow. Some are optional. Others are required.</p> <p>To simplify some initial validation I have a custom attribute that marks an event as a required one. For example:</p> <pre><code> [RequiredEventSubscription("This event is required!")] public event EventHandler ServiceStarted; </code></pre> <p>So far so good. To validate all events, using reflection I iterate the event list and grab the custom attributes. But I need a way to determine if the event is subscribed or not.</p> <p>Without reflection the ServiceStarted.GetInvocationList does the job. But the event must come from this list: var eventList = this.GetType().GetEvents().ToList();</p> <p>Is there any way to check if a given event, from an event list, is subscribed using reflection?</p> <p>--[Update]-- Here's a possible solution based on Ami's answer:</p> <pre><code> private void CheckIfRequiredEventsAreSubscribed() { var eventList = GetType().GetEvents().ToList().Where(e =&gt; Attribute.IsDefined(e, typeof(RequiredEventSubscription))); StringBuilder exceptionMessage = new StringBuilder(); StringBuilder warnMessage = new StringBuilder(); foreach (var evt in eventList) { RequiredEventSubscription reqAttr = (RequiredEventSubscription) evt.GetCustomAttributes(typeof(RequiredEventSubscription), true).First(); var evtDelegate = this.GetType().GetField(evt.Name, BindingFlags.Instance | BindingFlags.NonPublic); if (evtDelegate.GetValue(this) == null) { warnMessage.AppendLine(reqAttr.warnMess); if (reqAttr.throwException) exceptionMessage.AppendLine(reqAttr.warnMess); } } if (warnMessage.Length &gt; 0) Console.WriteLine(warnMessage); if (exceptionMessage.Length &gt; 0) throw new RequiredEventSubscriptionException(exceptionMessage.ToString()); } </code></pre> <p>Many thanks!!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload