SoFunction
Updated on 2025-03-07

Usage of observable sets of C# collections

If you need information about when an element in a collection is deleted or added, you can use the ObservableCollection<T> class. This class is defined for WPF so that the UI can know the changes in the collection. This class is defined in the assembly WindowsBase and needs to reference this assembly.
The ObservableCollection<T> class derives from the Collection<T> base class, which can be used to create custom collections and use the List<T> class internally. Rewrite the virtual methods SetItem() and RemoveItem() of the base class to trigger the CollectionChanged event.

static void Main()
        {
          var data = new ObservableCollection<string>();
           += Data_CollectionChanged;
          ("One");
          ("Two");
          (1, "Three");
          ("One");

        }

        static void Data_CollectionChanged(object sender,  e)
        {
          ("action: {0}", ());

          if ( != null)
          {
            ("starting index for old item(s): {0}", );
            ("old item(s):");
            foreach (var item in )
            {
              (item);
            }
          }
          if ( != null)
          {
            ("starting index for new item(s): {0}", );
            ("new item(s): ");
            foreach (var item in )
            {
              (item);
            }
          }

          ();
        }

This is all about this article about observable collections of C# collections. I hope it will be helpful to everyone's learning and I hope everyone will support me more.