<p>The compiler usually chokes when an event doesn't appear beside a <code>+=</code> or a <code>-=</code>, so I'm not sure if this is possible.</p>

<p>I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:</p>

<pre><code>using(var foo = new EventWatcher(target, x =&gt; x.MyEventToWatch) {
    // act here
}   // throws on Dispose() if MyEventToWatch hasn't fired
</code></pre>

<p>My questions are twofold:</p>

<ol>
<li>Will the compiler choke? And if so, any suggestions on how to prevent this?</li>
<li>How can I parse the Expression object from the constructor in order to attach to the <code>MyEventToWatch</code> event of <code>target</code>?</li>
</ol>

[{'answer_id': 36255, 'author': 'Curt Hagenlocher', 'author_id': 533, 'author_profile': 'https://Stackoverflow.com/users/533', 'pm_score': 2, 'selected': False, 'text': "<p>A .NET event isn't actually an object, it's an endpoint represented by two functions -- one for adding and one for removing a handler.  That's why the compiler won't let you do anything other than += (which represents the add) or -= (which represents the remove).</p>\n\n<p>The only way to refer to an event for metaprogramming purposes is as a System.Reflection.EventInfo, and reflection is probably the best way (if not the only way) to get ahold of one.</p>\n\n<p>EDIT: Emperor XLII has written some beautiful code which should work for your own events, provided you've declared them from C# simply as</p>\n\n<pre><code>public event DelegateType EventName;\n</code></pre>\n\n<p>That's because C# creates two things for you from that declaration:</p>\n\n<ol>\n<li>A private delegate field to serve as the backing\nstorage for the event</li>\n<li>The actual event along with\nimplementation code that makes use\nof the delegate.</li>\n</ol>\n\n<p>Conveniently, both of these have the same name.  That's why the sample code will work for your own events.</p>\n\n<p>However, you can't rely on this to be the case when using events implemented by other libraries.  In particular, the events in Windows Forms and in WPF don't have their own backing storage, so the sample code will not work for them.</p>\n"}, {'answer_id': 37315, 'author': 'Emperor XLII', 'author_id': 2495, 'author_profile': 'https://Stackoverflow.com/users/2495', 'pm_score': 3, 'selected': True, 'text': '<p><strong>Edit:</strong> As <a href="https://stackoverflow.com/questions/35211/identify-an-event-via-a-linq-expression-tree#36255">Curt</a> has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event :) Instead of "<code>x =&gt; x.MyEvent</code>" returning the event, it was returning the backing field, which is only accessble by the class.</p>\n\n<p>Since expressions cannot contain assignment statements, a modified expression like "<code>( x, h ) =&gt; x.MyEvent += h</code>" cannot be used to retrieve the event, so reflection would need to be used instead. A correct implementation would need to use reflection to retrieve the <code>EventInfo</code> for the event (which, unfortunatley, will not be strongly typed).</p>\n\n<p>Otherwise, the only updates that need to be made are to store the reflected <code>EventInfo</code>, and use the <code>AddEventHandler</code>/<code>RemoveEventHandler</code> methods to register the listener (instead of the manual <code>Delegate</code> <code>Combine</code>/<code>Remove</code> calls and field sets). The rest of the implementation should not need to be changed. Good luck :)</p>\n\n<hr>\n\n<p><strong>Note:</strong> This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader ;)</p>\n\n<pre><code>public sealed class EventWatcher : IDisposable {\n  private readonly object target_;\n  private readonly string eventName_;\n  private readonly FieldInfo eventField_;\n  private readonly Delegate listener_;\n  private bool eventWasRaised_;\n\n  public static EventWatcher Create&lt;T&gt;( T target, Expression&lt;Func&lt;T,Delegate&gt;&gt; accessor ) {\n    return new EventWatcher( target, accessor );\n  }\n\n  private EventWatcher( object target, LambdaExpression accessor ) {\n    this.target_ = target;\n\n    // Retrieve event definition from expression.\n    var eventAccessor = accessor.Body as MemberExpression;\n    this.eventField_ = eventAccessor.Member as FieldInfo;\n    this.eventName_ = this.eventField_.Name;\n\n    // Create our event listener and add it to the declaring object\'s event field.\n    this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType );\n    var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;\n    var newEventList = Delegate.Combine( currentEventList, this.listener_ );\n    this.eventField_.SetValue( this.target_, newEventList );\n  }\n\n  public void SetEventWasRaised( ) {\n    this.eventWasRaised_ = true;\n  }\n\n  private Delegate CreateEventListenerDelegate( Type eventType ) {\n    // Create the event listener\'s body, setting the \'eventWasRaised_\' field.\n    var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" );\n    var body = Expression.Call( Expression.Constant( this ), setMethod );\n\n    // Get the event delegate\'s parameters from its \'Invoke\' method.\n    var invokeMethod = eventType.GetMethod( "Invoke" );\n    var parameters = invokeMethod.GetParameters( )\n        .Select( ( p ) =&gt; Expression.Parameter( p.ParameterType, p.Name ) );\n\n    // Create the listener.\n    var listener = Expression.Lambda( eventType, body, parameters );\n    return listener.Compile( );\n  }\n\n  void IDisposable.Dispose( ) {\n    // Remove the event listener.\n    var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;\n    var newEventList = Delegate.Remove( currentEventList, this.listener_ );\n    this.eventField_.SetValue( this.target_, newEventList );\n\n    // Ensure event was raised.\n    if( !this.eventWasRaised_ )\n      throw new InvalidOperationException( "Event was not raised: " + this.eventName_ );\n  }\n}\n</code></pre>\n\n<p>Usage is slightly different from that suggested, in order to take advantage of type inference:</p>\n\n<pre><code>try {\n  using( EventWatcher.Create( o, x =&gt; x.MyEvent ) ) {\n    //o.RaiseEvent( );  // Uncomment for test to succeed.\n  }\n  Console.WriteLine( "Event raised successfully" );\n}\ncatch( InvalidOperationException ex ) {\n  Console.WriteLine( ex.Message );\n}\n</code></pre>\n'}, {'answer_id': 5521046, 'author': 'bryanbcook', 'author_id': 30809, 'author_profile': 'https://Stackoverflow.com/users/30809', 'pm_score': 1, 'selected': False, 'text': '<p>While Emperor XLII already gave the answer for this, I thought it was worth while to share my rewrite of this.  Sadly, no ability to get the Event via Expression Tree, I\'m using the name of the Event.</p>\n\n<pre><code>public sealed class EventWatcher : IDisposable {\n     private readonly object _target;\n     private readonly EventInfo _eventInfo;\n     private readonly Delegate _listener;\n     private bool _eventWasRaised;\n\n     public static EventWatcher Create&lt;T&gt;(T target, string eventName) {\n         EventInfo eventInfo = typeof(T).GetEvent(eventName);\n         if (eventInfo == null)\n            throw new ArgumentException("Event was not found.", eventName);\n         return new EventWatcher(target, eventInfo);\n     }\n\n     private EventWatcher(object target, EventInfo eventInfo) {\n         _target = target;\n         _eventInfo = event;\n         _listener = CreateEventDelegateForType(_eventInfo.EventHandlerType);\n         _eventInfo.AddEventHandler(_target, _listener);\n     }\n\n     // SetEventWasRaised()\n     // CreateEventDelegateForType\n\n     void IDisposable.Dispose() {\n         _eventInfo.RemoveEventHandler(_target, _listener);\n         if (!_eventWasRaised)\n            throw new InvalidOperationException("event was not raised.");\n     }\n}\n</code></pre>\n\n<p>And usage is:</p>\n\n<pre><code>using(EventWatcher.Create(o, "MyEvent")) {\n    o.RaiseEvent();\n}\n</code></pre>\n'}, {'answer_id': 11084822, 'author': 'sacha barber', 'author_id': 1089655, 'author_profile': 'https://Stackoverflow.com/users/1089655', 'pm_score': 2, 'selected': False, 'text': '<p>I too wanted to do this, and I have come up with a pretty cool way that does something like Emperor XLII idea. It doesn\'t use Expression trees though, as mentioned this can\'t be done as Expression trees do not allow the use of <code>+=</code> or <code>-=</code>. </p>\n\n<p>We can however use a neat trick where we use .NET Remoting Proxy (or any other Proxy such as LinFu or Castle DP) to intercept a call to Add/Remove handler on a very short lived proxy object. The role of this proxy object is to simply have some method called on it, and to allow its method calls to be intercepted, at which point we can find out the name of the event.</p>\n\n<p>This sounds weird but here is the code (which by the way ONLY works if you have a <code>MarshalByRefObject</code> or an interface for the proxied object)</p>\n\n<p>Assume we have the following interface and class</p>\n\n<pre><code>public interface ISomeClassWithEvent {\n    event EventHandler&lt;EventArgs&gt; Changed;\n}\n\n\npublic class SomeClassWithEvent : ISomeClassWithEvent {\n    public event EventHandler&lt;EventArgs&gt; Changed;\n\n    protected virtual void OnChanged(EventArgs e) {\n        if (Changed != null)\n            Changed(this, e);\n    }\n}\n</code></pre>\n\n<p>Then we can have a very simply class that expects an <code>Action&lt;T&gt;</code> delegate that will get passed some instance of <code>T</code>. </p>\n\n<p>Here is the code</p>\n\n<pre><code>public class EventWatcher&lt;T&gt; {\n    public void WatchEvent(Action&lt;T&gt; eventToWatch) {\n        CustomProxy&lt;T&gt; proxy = new CustomProxy&lt;T&gt;(InvocationType.Event);\n        T tester = (T) proxy.GetTransparentProxy();\n        eventToWatch(tester);\n\n        Console.WriteLine(string.Format("Event to watch = {0}", proxy.Invocations.First()));\n    }\n}\n</code></pre>\n\n<p>The trick is to pass the proxied object to the <code>Action&lt;T&gt;</code> delegate provided. </p>\n\n<p>Where we have the following <code>CustomProxy&lt;T&gt;</code> code, who intercepts the call to <code>+=</code> and <code>-=</code> on the proxied object</p>\n\n<pre><code>public enum InvocationType { Event }\n\npublic class CustomProxy&lt;T&gt; : RealProxy {\n    private List&lt;string&gt; invocations = new List&lt;string&gt;();\n    private InvocationType invocationType;\n\n    public CustomProxy(InvocationType invocationType) : base(typeof(T)) {\n        this.invocations = new List&lt;string&gt;();\n        this.invocationType = invocationType;\n    }\n\n    public List&lt;string&gt; Invocations {\n        get { \n            return invocations; \n        }\n    }\n\n    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]\n    [DebuggerStepThrough]\n    public override IMessage Invoke(IMessage msg) {\n        String methodName = (String) msg.Properties["__MethodName"];\n        Type[] parameterTypes = (Type[]) msg.Properties["__MethodSignature"];\n        MethodBase method = typeof(T).GetMethod(methodName, parameterTypes);\n\n        switch (invocationType) {\n            case InvocationType.Event:\n                invocations.Add(ReplaceAddRemovePrefixes(method.Name));\n                break;\n            // You could deal with other cases here if needed\n        }\n\n        IMethodCallMessage message = msg as IMethodCallMessage;\n        Object response = null;\n        ReturnMessage responseMessage = new ReturnMessage(response, null, 0, null, message);\n        return responseMessage;\n    }\n\n    private string ReplaceAddRemovePrefixes(string method) {\n        if (method.Contains("add_"))\n            return method.Replace("add_","");\n        if (method.Contains("remove_"))\n            return method.Replace("remove_","");\n        return method;\n    }\n}\n</code></pre>\n\n<p>And then we all that\'s left is to use this as follows</p>\n\n<pre><code>class Program {\n    static void Main(string[] args) {\n        EventWatcher&lt;ISomeClassWithEvent&gt; eventWatcher = new EventWatcher&lt;ISomeClassWithEvent&gt;();\n        eventWatcher.WatchEvent(x =&gt; x.Changed += null);\n        eventWatcher.WatchEvent(x =&gt; x.Changed -= null);\n        Console.ReadLine();\n    }\n}\n</code></pre>\n\n<p>Doing this I will see this output:</p>\n\n<pre><code>Event to watch = Changed\nEvent to watch = Changed\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/35211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']