A project I'm working on requires me to be able to fire off an event everytime an item is added to a list. To achieve this, I created a custom List class inheriting from List and added a OnAdd event. I also want to return the item being added as EventArgs for which I added some more code (given below):
public class ClientListObservable<Client>:List<Client>
{
public event EventHandler<EventArgs<Client>> OnAdd;
public void Add(Client item)
{
if (null != OnAdd)
{
OnAdd(this, new EventArgs<Client>(item));
}
base.Add(item);
}
}
public class EventArgs<Client> : EventArgs
{
public EventArgs(Client value)
{
m_value = value;
}
private Client m_value;
public Client Value
{
get { return m_value; }
}
}
This is how I add a handler
clientList.OnAdd += new EventHandler<EventArgs<Client>>(clientList_OnAdd);
But, in the OnAdd method:
private void clientList_OnAdd(object sender, EventArgs e)
{
//want to be able to access the data members of the Client object added
}
I can only access e.Equals, e.GetHashCode, e.GetType and e.ToString, and none of the members of Client class.
Change your event args to:
public class ClientEventArgs : EventArgs
{
public ClientEventArgs(Client value)
{
m_value = value;
}
private Client m_value;
public Client Value
{
get { return m_value; }
}
}
Then:
private void clientList_OnAdd(object sender, ClientEventArgs e)
{
Client client = e.Value;
}
Shouldn't your event handler be declared like this:
private void clientList_OnAdd(object sender, EventArgs<Client> e)
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With