A programming question about delegate and event

Yes, I don’t know what I am doing…

From ProgramOne.cs, what is the proper way to remove/stop further events from ProgramTwo.cs

I tried Delegate.Remove but I could not determine the correct syntax to use.
(Not really sure if Delegate.Remove is even intended for what I want to do.)

At some point in ProgramOne I want to stop receiving events from Program2 (not just ignore them) and at some point potentiality resume events.


namespace A

         Closed += new ClosedEventHandler(Closed);
        void Closed()
	//Do something when event received
// End

namespace B

        public delegate void ClosedEventHandler();
        public static event ClosedEventHandler Closed;

         // On event
        protected virtual void OnClose()
             // I can prevent further events from occurring by using this..
             // There must be a better (proper) way.

            if (Closed != null)
            if (Closed != null)
                // Prevent further events
                Closed -= Closed;

        protected override void OnDoingSomething( )
// End

To add a listener to an event:

 Closed += new ClosedEventHandler(Closed);

To remove that listener from the event:

Closed -= new ClosedEventHandler(Closed);

+= to add, -= to remove.

However, it’s terribly counterintuitive to have to construct something in order to remove it, so I prefer the simpler function identifier syntax:


obj.Closed += foo.MyClosedFunction;


obj.Closed -= foo.MyClosedFunction;

You don’t actually need to construct the delegate yourself. Just specify the name of a function with a compatible parameter list and C# will construct the delegate for you behind the scenes.

p.s. Consider renaming your event handler function to something different from the event you want to assign it to. Regardless of whether the C# compiler can figure out what you’re trying to do or not, Closed += Closed makes everyone crosseyed. ;>

Thank you for the quick reply!

Closed += Closed makes everyone crosseyed

Not the actual code. Just something I threw together to try and explain my question…
You understood so I guess it was good enough.

Thanks again!