title: How to have Lists with events upon change in List
body: <p>I'm a newbie in events.  <a href="http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx" rel="nofollow">This example</a> shows that an event is invoked every time the ArrayList is changed.  I would like to know how to do it using generics.  To you implement IList or extend List?  I tried to code it but I'm stuck.</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  
  namespace Events
  {
      public delegate void ChangedEventHandler(object sender, EventArgs e);
  
      public class ListWithChangedEvent&lt;T&gt; : IList&lt;T&gt;
      {
          public event ChangedEventHandler Changed;
  
          protected virtual void OnChanged(EventArgs e)
          {
              if (Changed != null)
              {
                  Changed(this, e);
              }
          }
  
          public void Add(T value)
          {
              base.Add(value);
              OnChanged(EventArgs.Empty);
          }
  
          public void Clear()
          {
              base.Clear();
              OnChanged(EventArgs.Empty);
          }
  
          public T this[int index]
          {
              set
              {
                  base[index] = value;
                  OnChanged(EventArgs.Empty);
              }
          }
      }
  
      class EventListener
      {
          private ListWithChangedEvent&lt;string&gt; List;
  
          public EventListener(ListWithChangedEvent&lt;string&gt; list)
          {
              List = list;
              List.Changed += new ChangedEventHandler(ListChanged);
          }
  
          private void ListChanged(object sender, EventArgs e)
          {
              Console.WriteLine("This is called when the event fires.");
          }
  
          public void Detach()
          {
              List.Changed -= new ChangedEventHandler(ListChanged);
              List = null;
          }
      }
  
      class Program
      {
          public static void Main(string[] args)
          {
              ListWithChangedEvent&lt;string&gt; list = new ListWithChangedEvent&lt;string&gt;();
  
              EventListener listener = new EventListener(list);
  
              list.Add("item 1");
              list.Clear();
              listener.Detach();
          }
      }
  }
  </code></pre>