I want to use the OnCreateFeature-Event to combine it with other actions. So I use

Events.OnCreateFeature += delegate(IObject obj) { LoopTools_OnCreateFeature(obj); };

to listen to this event. That works very well.

But how can I stop listening? I tried

Events.OnCreateFeature -= delegate(IObject obj) { LoopTools_OnCreateFeature(obj); };

but this didn't release the event. So when I looped through some sweeps, it happened that I have wired the event two or more times and the corresponding actions are done to often. I also tried

Events.OnCreateFeature -= LoopTools_OnCreateFeature;

but that has the same effect. What am I doing wrong?

I'm thankful for any suggestions.


In your code, you are subscribing to an event using an anonymous method delegate. When you need to unsubscribe from an event, it is generally easier and more readable to use non-anonymous methods (note this is C# 3 or higher code, C# 2 would need to be a bit more verbose):

// subscribe
Events.OnCreateFeature += OnCreateFeature;

// unsubscribe
Events.OnCreateFeature -= OnCreateFeature;

The method that gets called when the event is raised then looks like:

public void OnCreateFeature(IObject object)

But anonymous methods can be unsubscribed as well, you just need to keep the reference to the delegate around (I assume your OnCreateFeature event comes from IEditEvents):

IEditEvents_OnCreateFeatureEventHandler onCreateFeatureDelegate = delegate(IObject obj) { LoopTools_OnCreateFeature(obj); };

// subscribe
Events.OnCreateFeature += onCreateFeatureDelegate;

// unsubscribe
Events.OnCreateFeature -= onCreateFeatureDelegate;

As you probably see by now, you'd most likely need to keep the onCreateFeatureDelegate reference as a class field in contrast to a local variable as shown in the sample. That's why I believe the first approach is more readable and does not clutter your code excessively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy