Event Handling Standard Pattern With Event Args Parameter C# with Example



Event Handling Standard Pattern With Event Args Parameter C# with Example

 	using System;

	namespace CSharpEvents
	{
		public class PublisherEventArgs : EventArgs
		{
			public int extraData { get; set; }
		} 

		class Publisher
		{
			public event EventHandler valueChanged;		//Event Declared
			
			public void FireEvent(int value)
			{
				PublisherEventArgs args = new PublisherEventArgs();
				args.extraData = value;
				if( value==3 && valueChanged != null)
					valueChanged(this, args);						//Raise or Trigger the Event 
			}
		}
	
		class Subscriber
		{
			public Subscriber(Publisher publisher)
			{
				publisher.valueChanged += EventHandler;
			}

			public void EventHandler(object source, PublisherEventArgs args)
			{
				Console.WriteLine("valueChanged Event Fired Successfully with value: " + args.extraData);
			}
		}
		
		class UsingEvent
		{
			public static void Main()
			{
				Publisher evtGenerator = new Publisher();
				Subscriber eventListener = new Subscriber(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