Event Example2 C# with Example



Event Example2 C# with Example

 	using System;

	namespace CSharpEvents
	{
		delegate void Handler();
		class Publisher
		{
			public event Handler valueChanged;			//Event Declared
			
			public void FireEvent(int value)
			{
				if( value==3 && valueChanged != null)
					valueChanged();						//Raise or Trigger the Event 
			}
		}
	
		class Subscriber
		{
			public Subscriber(Publisher publisher)
			{
				publisher.valueChanged += EventHandler;
			}

			public void EventHandler()
			{
				Console.WriteLine("Event Handler of Subscriber for valueChanged Event.");
			}
		}

		class Subscriber1
		{
			public Subscriber1(Publisher publisher)
			{
				publisher.valueChanged += EventHandler;
			}

			public void EventHandler()
			{
				Console.WriteLine("Event Handler of Subscriber1 for valueChanged Event.");
			}
		}
		
		class UsingEvent
		{
			public static void Main()
			{
				Publisher evtGenerator = new Publisher();
				Subscriber eventListener = new Subscriber(evtGenerator);
				Subscriber1 eventListener1 = new Subscriber1(evtGenerator);
				
				int number;
				do
				{
					Console.Write("Enter a Number: ");
					number = Convert.ToInt32(Console.ReadLine());
					evtGenerator.FireEvent(number);
					
					if(number == 3)
						return;
					else
						Console.WriteLine("Event Not Fired. Try Something Else.\n");
				}while(number != 3);
			}
		}
	}
 

0 Comment's

Comment Form

Submit Comment