C# Workshop – Events

Standard

Events

Events are a way for a class to provide notifications when something interesting has happened to an object, for example in a user experience with a button when you tap the button this would be an event that has occurred, however they aren’t just for user experiences but are useful to indicate a change of state that might be of use to something.
Events in can be created using something known as a delegate which is a type that represents or encapsulates a Method with a set of parameters and a return type.

An example of using an event and delegate in dotnetfiddle.net, enter the following:

using System;

public class Demo
{	
	public delegate void ChangedHandler(int number);

	public static event ChangedHandler Changed;

	private static void OnChanged(int number) 
	{
		Console.WriteLine(number);
	}

	public static void Main()
	{
		Changed += new ChangedHandler(OnChanged);
		Changed(10);
	}
}

In this example, there is the delegate which is has the Signature of the event to use that would be the parameters it will use in this case it is an int called number. Then there is the event which uses the Delegate as its type, this would be what would be called to make the event occur. Then there is a Method which also matches the Signature of the delegate and takes the same Parameters. In the Main Method, there is the event and a new operator += which in this case is used specify the method that will be called in response to an event which is a method with the same signature as the delegate and the OnChanged Method to be called when the event occurs, then we raise the event by calling that Method and pass in a value.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s