All pastes #246893 Raw Edit

zeroflag

public text v1 · immutable
#246893 ·published 2006-11-12 20:36 UTC
rendered paste body
class MyClass
{
	/// <summary>
	/// First, the delegate for the handler. This defines how the subscriber-methods have to look like.
	/// </summary>
	/// <remarks>You don't need that "sender" object but most events have it... not much point there but, hey, it's common...</remarks>
	public delegate void MyEventHandler(object sender, int param);

	/// <summary>
	/// Next up, a PRIVATE event of that type.
	/// </summary>
	private event MyEventHandler m_MyEvent;

	/// <summary>
	/// Third, the public add/remove access to the event. It is NOT possible to RAISE the event through this interface (which is good).
	/// </summary>
	public event MyEventHandler MyEvent
	{
		add
		{
			// this allows listeners to subscribe to the event...
			m_MyEvent += value;
		}

		remove
		{
			// this allows to unsubscribe...
			m_MyEvent -= value;
		}
	}


	/// <summary>
	/// The event "raisor". It raises the event for us. Noone is to raise the event except this method.
	/// You want to make it protected, so noone from the outside can raise the event. (would be stupid in most cases)
	/// You want to make it virtual, so a derived class can "disable" the event by overriding this method.
	/// </summary>
	/// <param name="param"></param>
	protected virtual void OnMyEvent(int param)
	{
		// first, check if there are any subscribers (the event will be null if there are none)...
		if (m_MyEvent != null)
		{
			// call the event. the "sender" object is always set to the class who raises the event.
			m_MyEvent(this, param);
		}
	}
}

class MyListener
{
	MyClass myInstance = new MyClass();

	public void Subscribe()
	{
		myInstance.MyEvent += new MyClass.MyEventHandler(myInstance_MyEvent);
	}

	void myInstance_MyEvent(object sender, int param)
	{
		//TODO: do something.
	}
}

class MyDerivedClass : MyClass
{
	protected override void OnMyEvent(int param)
	{
		// Disable the event.
		//base.OnMyEvent(param);
	}
}