I am learning Events and Delegates & started with multiple events now. Just that the docs does not supply any information or code example to raising events defined in this manner.Below you can find a simple example
Sample Code
public class Person
{
private string _name;
private string _phone;
public string Name
{
get { return _name; }
set
{
_name = value;
}
}
public string Phone
{
get { return _phone; }
set
{
_phone = value;
}
}
protected EventHandlerList EventDelegateCollection = new EventHandlerList();
//define the event key
static readonly object PhoneChangedEventKey = new object();
public event EventHandler PhoneChanged
{
add
{
EventDelegateCollection.AddHandler(PhoneChangedEventKey, value);
}
remove
{
EventDelegateCollection.RemoveHandler(PhoneChangedEventKey, value);
}
}
}
I would like to raise the event when the Phone number is set. if anything sounds funky and don't understand what i am talking about see here
Update
I would like to clear some doubts here. There are Two ways you can actually subscribe and invoke the event handlers the classical pattern(as described here) where the steps are
- Define the delegate that acts as signature for subscribed methods.
- Define the Event that delegates
- Define the method that raises the handlers
note:
above method creates field for every event hence consumes more memory reference
Event Property is another way where you do below
- Define a object that acts as Key to a event
- Define a method to add and remove handlers for the event from the event invocation list
- Raise the event by determining event handlers based on event key