Snippets code #1 - Extension method to raise an event via reflection

This extension method, applied to the object class and then available for all classes, allows to raise any events via reflection, providing as parameters the event name (as a string) and the TEvenArgs generic parameter.

public static void Raise<TEventArgs>(this object source, string eventName, 
          TEventArgs eventArgs) where TEventArgs : EventArgs
{
     var eventInfo = source.GetType().GetEvent(eventName, 
               BindingFlags.Public | BindingFlags.NonPublic 
             | BindingFlags.Instance);
     var eventDelegate = (MulticastDelegate)source.GetType()
            .GetField(eventName, BindingFlags.Instance 
            | BindingFlags.NonPublic).GetValue(source);
     if (eventDelegate != null)
     {
         foreach (var handler in eventDelegate.GetInvocationList())
         {
             handler.Method.Invoke(handler.Target, 
                       new object[] { source, eventArgs });
         }
      }
}

Example of use:

CustomerViewModel vm = new CustomerViewModel();
vm.Raise("PropertyChanged", new PropertyChangedEventArgs("Name"));

Source for code in this example

Print | posted on Friday, September 23, 2011 12:00 AM

Comments on this post

No comments posted yet.

Your comment:

 (will show your gravatar)
 
Please add 3 and 5 and type the answer here: