4

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.

Ayush
  • 41,754
  • 51
  • 164
  • 239

4 Answers4

6

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;
    }
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

Shouldn't your event handler be declared like this:

private void clientList_OnAdd(object sender, EventArgs<Client> e)

?

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
  • The class declaration won't work, either, there... It's not `EventHandler` here. There is no `EventArgs`. See: http://stackoverflow.com/questions/3312134/does-net-have-a-built-in-eventargst – Reed Copsey Feb 09 '11 at 19:44
  • @Reed, I know -- I had assumed the OP had written that variant himself (which his code shows he did.) – Kirk Woll Feb 09 '11 at 20:31
1

you should derive your custom class from EventArgs and have a member to host your custom objects in there, then you should invoke the event passing such specialized EventArgs which you would have created and initialized as needed.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
1

Create your own event args that extends EventArgs and has a public property of a "Client" object. Then on add populate the custom EventArgs with the new item and return it.

William
  • 1,457
  • 5
  • 21
  • 46