{"id":69,"date":"2007-09-19T08:07:40","date_gmt":"2007-09-19T07:07:40","guid":{"rendered":"http:\/\/thekua.com\/atwork\/2007\/09\/19\/events-reflection-and-how-they-dont-work-in-c\/"},"modified":"2007-09-19T08:07:40","modified_gmt":"2007-09-19T07:07:40","slug":"events-reflection-and-how-they-dont-work-in-c","status":"publish","type":"post","link":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/","title":{"rendered":"Events, Reflection and how they don&#8217;t work in C#"},"content":{"rendered":"<p>Although the .Net reflection APIs make some tasks easier, we&#8217;ve found recently that those related to events and their delegates have been fairly poorly designed. Our task was very simple: dynamically manipulate the event handlers attached to a set of events. <\/p>\n<p>It&#8217;s easy enough to get a declaration about an event of some sort using code like: <\/p>\n<pre>EventInfo infoAboutEvent = someObject.GetType().GetEvent(\"MyEvent\"); <\/pre>\n<p>Given your <code>EventInfo<\/code> class it&#8217;s easy to add an a new event handler. Unfortunately going the other way around ended up much harder. Unlike things like <code>FieldInfo<\/code> that give you direct access to get the field instance from the object using <code>GetValue(owner)<\/code>, finding the event field isn&#8217;t as easy. First we had to look at all the fields, and filtered out things that looked like a Delegate so we could do some useful things with them, like finding out what subscribers were hooked up to our event. <\/p>\n<p>Our ultimate goal of being able to dynamically remove <code>EventHandler<\/code>s at runtime further ran into problems when we were trying to unhook methods from private events. The result of trying to unhook a handler from a private event via the <code>EventInfo.RemoveEventHandler<\/code> method results in an <code>InvalidOperationException<\/code> with a message of &#8220;Cannot remove the event handler since no public remove method exists for the event.&#8221;<\/p>\n<p>One more simple use of reflection and soon we were able to automatically unhook a variety of delegates from our events regardless of their access mechanism (although using code that wasn&#8217;t as nice as we wanted). A few refactorings later and we ended up with something actually quite useful in the end.<\/p>\n<pre>\r\nReflectUtil.RemoveEventHandlersFrom(\r\n delegate(Delegate subject) { return subject.Method.Name.StartsWith(\"On\"); }, \r\n  objectWithEvent);\r\n<\/pre>\n<p>And here&#8217;s the class that we ended up with. Although I can&#8217;t recommend people use reflection lightly, if you need to delve into the world of reflection with events, I hope you find this example useful.<\/p>\n<pre>\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Globalization;\r\nusing System.Reflection;\r\n\r\npublic sealed class ReflectUtil\r\n{\r\n  private static BindingFlags PrivatePublicStaticInstance \r\n    = BindingFlags.NonPublic | BindingFlags.Public |\r\n      BindingFlags.Instance | BindingFlags.Static;\r\n\r\n  public delegate bool MatchesOnDelegate(Delegate subject);\r\n\r\n  public static void RemoveEventHandlersFrom(\r\n    MatchesOnDelegate matchesOnDelegate, params object[] objectsWithEvents)\r\n  {\r\n    foreach (object owningObject in objectsWithEvents)\r\n    {\r\n      foreach (DelegateInfo eventFromOwningObject in GetDelegates(owningObject))\r\n      {\r\n        foreach (Delegate subscriber in eventFromOwningObject.GetInvocationList())\r\n        {\r\n          if (matchesOnDelegate(subscriber))\r\n          {\r\n            EventInfo theEvent = eventFromOwningObject.GetEventInfo();\r\n            RemoveSubscriberEvenIfItsPrivate(theEvent, owningObject, subscriber);\r\n          }\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  \/\/ You can use eventInfo.RemoveEventHandler(owningObject, subscriber) \r\n  \/\/ unless it's a private delegate\r\n  private static void RemoveSubscriberEvenIfItsPrivate(\r\n    EventInfo eventInfo, object owningObject, Delegate subscriber)\r\n  {\r\n    MethodInfo privateRemoveMethod = eventInfo.GetRemoveMethod(true);\r\n    privateRemoveMethod.Invoke(owningObject,\r\n                               PrivatePublicStaticInstance, null, \r\n                               new object[] {subscriber}, CultureInfo.CurrentCulture);\r\n  }\r\n\r\n  private static DelegateInfo[] GetDelegates(object owningObject)\r\n  {\r\n    List<DelegateInfo> delegates = new List<DelegateInfo>();\r\n    FieldInfo[] allPotentialEvents = owningObject.GetType()\r\n      .GetFields(PrivatePublicStaticInstance);\r\n    foreach (FieldInfo privateFieldInfo in allPotentialEvents)\r\n    {\r\n      Delegate eventFromOwningObject = privateFieldInfo.GetValue(owningObject) \r\n        as Delegate;\r\n      if (eventFromOwningObject != null)\r\n      {\r\n        delegates.Add(new DelegateInfo(eventFromOwningObject, privateFieldInfo, \r\n          owningObject));\r\n      }\r\n    }\r\n    return delegates.ToArray();\r\n  }\r\n\r\n  private class DelegateInfo\r\n  {\r\n    private readonly Delegate delegateInformation;\r\n    private readonly FieldInfo fieldInfo;\r\n    private readonly object owningObject;\r\n\r\n    public DelegateInfo(Delegate delegateInformation, FieldInfo fieldInfo, \r\n      object owningObject)\r\n    {\r\n      this.delegateInformation = delegateInformation;\r\n      this.fieldInfo = fieldInfo;\r\n      this.owningObject = owningObject;\r\n    }\r\n\r\n    public Delegate[] GetInvocationList()\r\n    {\r\n      return delegateInformation.GetInvocationList();\r\n    }\r\n\r\n    public EventInfo GetEventInfo()\r\n    {\r\n      return owningObject.GetType().GetEvent(fieldInfo.Name, \r\n        PrivatePublicStaticInstance);\r\n    }\r\n  }\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Although the .Net reflection APIs make some tasks easier, we&#8217;ve found recently that those related to events and their delegates have been fairly poorly designed. Our task was very simple: dynamically manipulate the event handlers attached to a set of events. It&#8217;s easy enough to get a declaration about an event of some sort using [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8,4],"tags":[],"class_list":["post-69","post","type-post","status-publish","format-standard","hentry","category-net","category-development","post-preview"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.3 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Events, Reflection and how they don&#039;t work in C# - patkua@work<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Events, Reflection and how they don&#039;t work in C# - patkua@work\" \/>\n<meta property=\"og:description\" content=\"Although the .Net reflection APIs make some tasks easier, we&#8217;ve found recently that those related to events and their delegates have been fairly poorly designed. Our task was very simple: dynamically manipulate the event handlers attached to a set of events. It&#8217;s easy enough to get a declaration about an event of some sort using [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/\" \/>\n<meta property=\"og:site_name\" content=\"patkua@work\" \/>\n<meta property=\"article:published_time\" content=\"2007-09-19T07:07:40+00:00\" \/>\n<meta name=\"author\" content=\"Patrick\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@patkua\" \/>\n<meta name=\"twitter:site\" content=\"@patkua\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Patrick\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/2007\\\/09\\\/events-reflection-and-how-they-dont-work-in-c\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/2007\\\/09\\\/events-reflection-and-how-they-dont-work-in-c\\\/\"},\"author\":{\"name\":\"Patrick\",\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/#\\\/schema\\\/person\\\/c942203c9ed3ff9e21c6c49a996ea3ae\"},\"headline\":\"Events, Reflection and how they don&#8217;t work in C#\",\"datePublished\":\"2007-09-19T07:07:40+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/2007\\\/09\\\/events-reflection-and-how-they-dont-work-in-c\\\/\"},\"wordCount\":308,\"commentCount\":5,\"articleSection\":[\".Net\",\"Development\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/thekua.com\\\/atwork\\\/2007\\\/09\\\/events-reflection-and-how-they-dont-work-in-c\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/2007\\\/09\\\/events-reflection-and-how-they-dont-work-in-c\\\/\",\"url\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/2007\\\/09\\\/events-reflection-and-how-they-dont-work-in-c\\\/\",\"name\":\"Events, Reflection and how they don't work in C# - patkua@work\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/#website\"},\"datePublished\":\"2007-09-19T07:07:40+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/#\\\/schema\\\/person\\\/c942203c9ed3ff9e21c6c49a996ea3ae\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/2007\\\/09\\\/events-reflection-and-how-they-dont-work-in-c\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/thekua.com\\\/atwork\\\/2007\\\/09\\\/events-reflection-and-how-they-dont-work-in-c\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/2007\\\/09\\\/events-reflection-and-how-they-dont-work-in-c\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Events, Reflection and how they don&#8217;t work in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/#website\",\"url\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/\",\"name\":\"patkua@work\",\"description\":\"The intersection of technology and leadership\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/#\\\/schema\\\/person\\\/c942203c9ed3ff9e21c6c49a996ea3ae\",\"name\":\"Patrick\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/2ef85a5f91c2aac13efb3ac90077b4db7f8883cafd6e60f2bcecba6b092d4011?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/2ef85a5f91c2aac13efb3ac90077b4db7f8883cafd6e60f2bcecba6b092d4011?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/2ef85a5f91c2aac13efb3ac90077b4db7f8883cafd6e60f2bcecba6b092d4011?s=96&d=mm&r=g\",\"caption\":\"Patrick\"},\"sameAs\":[\"http:\\\/\\\/thekua.com\\\/atwork\"],\"url\":\"https:\\\/\\\/thekua.com\\\/atwork\\\/author\\\/patrick\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Events, Reflection and how they don't work in C# - patkua@work","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/","og_locale":"en_US","og_type":"article","og_title":"Events, Reflection and how they don't work in C# - patkua@work","og_description":"Although the .Net reflection APIs make some tasks easier, we&#8217;ve found recently that those related to events and their delegates have been fairly poorly designed. Our task was very simple: dynamically manipulate the event handlers attached to a set of events. It&#8217;s easy enough to get a declaration about an event of some sort using [&hellip;]","og_url":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/","og_site_name":"patkua@work","article_published_time":"2007-09-19T07:07:40+00:00","author":"Patrick","twitter_card":"summary_large_image","twitter_creator":"@patkua","twitter_site":"@patkua","twitter_misc":{"Written by":"Patrick","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/#article","isPartOf":{"@id":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/"},"author":{"name":"Patrick","@id":"https:\/\/thekua.com\/atwork\/#\/schema\/person\/c942203c9ed3ff9e21c6c49a996ea3ae"},"headline":"Events, Reflection and how they don&#8217;t work in C#","datePublished":"2007-09-19T07:07:40+00:00","mainEntityOfPage":{"@id":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/"},"wordCount":308,"commentCount":5,"articleSection":[".Net","Development"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/","url":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/","name":"Events, Reflection and how they don't work in C# - patkua@work","isPartOf":{"@id":"https:\/\/thekua.com\/atwork\/#website"},"datePublished":"2007-09-19T07:07:40+00:00","author":{"@id":"https:\/\/thekua.com\/atwork\/#\/schema\/person\/c942203c9ed3ff9e21c6c49a996ea3ae"},"breadcrumb":{"@id":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/thekua.com\/atwork\/2007\/09\/events-reflection-and-how-they-dont-work-in-c\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/thekua.com\/atwork\/"},{"@type":"ListItem","position":2,"name":"Events, Reflection and how they don&#8217;t work in C#"}]},{"@type":"WebSite","@id":"https:\/\/thekua.com\/atwork\/#website","url":"https:\/\/thekua.com\/atwork\/","name":"patkua@work","description":"The intersection of technology and leadership","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/thekua.com\/atwork\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/thekua.com\/atwork\/#\/schema\/person\/c942203c9ed3ff9e21c6c49a996ea3ae","name":"Patrick","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2ef85a5f91c2aac13efb3ac90077b4db7f8883cafd6e60f2bcecba6b092d4011?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2ef85a5f91c2aac13efb3ac90077b4db7f8883cafd6e60f2bcecba6b092d4011?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2ef85a5f91c2aac13efb3ac90077b4db7f8883cafd6e60f2bcecba6b092d4011?s=96&d=mm&r=g","caption":"Patrick"},"sameAs":["http:\/\/thekua.com\/atwork"],"url":"https:\/\/thekua.com\/atwork\/author\/patrick\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/thekua.com\/atwork\/wp-json\/wp\/v2\/posts\/69","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thekua.com\/atwork\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thekua.com\/atwork\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thekua.com\/atwork\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/thekua.com\/atwork\/wp-json\/wp\/v2\/comments?post=69"}],"version-history":[{"count":0,"href":"https:\/\/thekua.com\/atwork\/wp-json\/wp\/v2\/posts\/69\/revisions"}],"wp:attachment":[{"href":"https:\/\/thekua.com\/atwork\/wp-json\/wp\/v2\/media?parent=69"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thekua.com\/atwork\/wp-json\/wp\/v2\/categories?post=69"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thekua.com\/atwork\/wp-json\/wp\/v2\/tags?post=69"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}