Understanding ObservableCollection<T> in C#
Tomer Kedem
Team Leader Full Stack | AI | C# | .NET | JavaScript | Angular | SQL | CI/CD
As a beginner programmer in C#, you might have encountered the need to work with collections that notify you about changes. This is where the ObservableCollection<T> class comes in handy. It's a part of the System.Collections.ObjectModel namespace and extends the functionalities of a regular collection by adding notifications when items get added, removed, or when the whole list is refreshed.
What is ObservableCollection<T>?
ObservableCollection<T> is a dynamic data collection that provides notifications when items are added, removed, or the entire list is refreshed. This makes it perfect for data-binding scenarios, particularly in MVVM (Model-View-ViewModel) architectures often used in WPF (Windows Presentation Foundation) applications.
Basic Usage
Here's a simple example to get you started:
using System;
using System.Collections.ObjectModel;
public class Program
{
public static void Main()
{
ObservableCollection<string> fruits = new ObservableCollection<string>();
fruits.CollectionChanged += (sender, e) => Console.WriteLine("Collection changed!");
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Remove("Apple");
}
}
In this example, we create an ObservableCollection of strings named fruits. We subscribe to the CollectionChanged event to get notified whenever the collection changes. Adding and removing items triggers this event, and you will see "Collection changed!" printed to the console.
Why Use ObservableCollection<T>?
Advanced Example
Here's a more advanced usage with a custom class:
using System;
using System.Collections.ObjectModel;
public class Person
{
public string Name { get; set; }
}
public class Program
{
public static void Main()
{
ObservableCollection<Person> people = new ObservableCollection<Person>();
people.CollectionChanged += (sender, e) => Console.WriteLine("People collection changed!");
people.Add(new Person { Name = "John" });
people.Add(new Person { Name = "Jane" });
}
}
In this example, we define a Person class and create an ObservableCollection of Person objects. Adding new Person instances triggers the CollectionChanged event.
Conclusion
ObservableCollection<T> is a powerful tool for managing dynamic data collections in C#. It simplifies data-binding, reduces code complexity, and ensures your UI stays in sync with your data.
Feel free to explore more about ObservableCollection<T> and integrate it into your projects. Start by adding it to a simple project and observe how it can improve your data management.
#CSharp #WPF #DataBinding #MVVM #TomerKedemQuiz