Removing Events Or Unsubscribing C# with Example



Removing Events Or Unsubscribing C# with Example

 	using System;

	namespace CSharpEvents
	{
		class Publisher
		{
			public event EventHandler simpleEvent;			//Event Declared
			
			public void FireEvent()
			{
				if( simpleEvent != null)
					simpleEvent(this, null);						//Raise or Trigger the Event 
			}
		}
	
		class Subscriber
		{
			public void EventHandler1(object source, EventArgs args)
			{
				Console.WriteLine("First Event Handler Executed.");
			}
			
			public void EventHandler2(object source, EventArgs args)
			{
				Console.WriteLine("Second Event Handler Executed.");
			}
			
			public void EventHandler3(object source, EventArgs args)
			{
				Console.WriteLine("Third Event Handler Executed.");
			}
		}
		
		class UsingEvent
		{
			public static void Main()
			{
				Publisher evtGenerator = new Publisher();
				Subscriber eventListener = new Subscriber();
				
				Console.WriteLine("After Adding all Event Handlers:");
				evtGenerator.simpleEvent += eventListener.EventHandler1;
				evtGenerator.simpleEvent += eventListener.EventHandler2;
				evtGenerator.simpleEvent += eventListener.EventHandler3;
				evtGenerator.FireEvent();
				
				Console.WriteLine("\nAfter Removing Event Handler2:");
				evtGenerator.simpleEvent -= eventListener.EventHandler2;
				evtGenerator.FireEvent();
			}
		}
	}
 

0 Comment's

Comment Form