Getting notified when collection changes with ObservableCollection in C# .NET

Imagine that you’d like to be notified when something is changed in a collection, e.g. an item is added or removed. One possible solution is to use the built-in .NET generic collection type ObservableCollection of T which is located in the System.Collections.ObjectModel namespace. The ObservableCollection object has an event called CollectionChanged. You can hook up an event handler to be notified of the changes.

If you don’t know what events, event handlers and delegates mean then start here.

Let’s see a simple example with a collection of strings:

ObservableCollection<string> names = new ObservableCollection<string>();
names.Add("Adam");
names.Add("Eve");
names.Add("Clive");
names.Add("Anne");
names.Add("John");
names.Add("Peter");
names.Add("Hannah");

Nothing special so far I guess. This looks exactly like a “normal” collection.

The following example demonstrates the CollectionChanged event:

private static void RunObservableCollectionCode()
{
	ObservableCollection<string> names = new ObservableCollection<string>();
	names.CollectionChanged += names_CollectionChanged;
	names.Add("Adam");
	names.Add("Eve");
	names.Remove("Adam");
	names.Add("John");
	names.Add("Peter");
	names.Clear();
}

static void names_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
	Debug.WriteLine("Change type: " + e.Action);
	if (e.NewItems != null)
	{
		Debug.WriteLine("Items added: ");
		foreach (var item in e.NewItems)
		{
			Debug.WriteLine(item);
		}
	}

	if (e.OldItems != null)
	{
		Debug.WriteLine("Items removed: ");
		foreach (var item in e.OldItems)
		{
			Debug.WriteLine(item);
		}
	}
}

The NotifyCollectionChangedEventArgs object resides in the System.Collections.Specialized namespace.

If I run the RunObservableCollectionCode method I get the following output:

Change type: Add
Items added:
Adam
Change type: Add
Items added:
Eve
Change type: Remove
Items removed:
Adam
Change type: Add
Items added:
John
Change type: Add
Items added:
Peter
Change type: Reset

You can then decide how to handle additions and deletions in the event handler.

View all various C# language feature related posts here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Getting notified when collection changes with ObservableCollection in C# .NET

  1. Linoy says:

    Good one (y)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: