What is the use of ObservableCollection in .net?
Solution 1
ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there. Code can add event handlers to see when the collection has changed and then react through the event handler to do some additional processing. This may be changing a UI or performing some other operation.
The code below doesn't really do anything but demonstrates how you'd attach a handler in a class and then use the event args to react in some way to the changes. WPF already has many operations like refreshing the UI built in so you get them for free when using ObservableCollections
class Handler
{
private ObservableCollection<string> collection;
public Handler()
{
collection = new ObservableCollection<string>();
collection.CollectionChanged += HandleChange;
}
private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
{
foreach (var x in e.NewItems)
{
// do something
}
foreach (var y in e.OldItems)
{
//do something
}
if (e.Action == NotifyCollectionChangedAction.Move)
{
//do something
}
}
}
Solution 2
An ObservableCollection
works essentially like a regular collection except that it implements
the interfaces:
As such it is very useful when you want to know when the collection has changed. An event is triggered that will tell the user what entries have been added/removed or moved.
More importantly they are very useful when using databinding on a form.
Solution 3
From Pro C# 5.0 and the .NET 4.5 Framework
The ObservableCollection<T>
class is very useful in that it has the ability to inform external objects
when its contents have changed in some way (as you might guess, working with
ReadOnlyObservableCollection<T>
is very similar, but read-only in nature).
In many ways, working with
the ObservableCollection<T>
is identical to working with List<T>
, given that both of these classes
implement the same core interfaces. What makes the ObservableCollection<T>
class unique is that this
class supports an event named CollectionChanged
. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified.
Like any event, CollectionChanged is defined in terms of a delegate, which in this case is
NotifyCollectionChangedEventHandler
. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs
as the second. Consider the following Main()
method, which populates an observable collection containing Person objects and wires up the
CollectionChanged
event:
class Program
{
static void Main(string[] args)
{
// Make a collection to observe and add a few Person objects.
ObservableCollection<Person> people = new ObservableCollection<Person>()
{
new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
};
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;
// Now add a new item.
people.Add(new Person("Fred", "Smith", 32));
// Remove an item.
people.RemoveAt(0);
Console.ReadLine();
}
static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// What was the action that caused the event?
Console.WriteLine("Action for this event: {0}", e.Action);
// They removed something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
Console.WriteLine("Here are the OLD items:");
foreach (Person p in e.OldItems)
{
Console.WriteLine(p.ToString());
}
Console.WriteLine();
}
// They added something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
// Now show the NEW items that were inserted.
Console.WriteLine("Here are the NEW items:");
foreach (Person p in e.NewItems)
{
Console.WriteLine(p.ToString());
}
}
}
}
The incoming NotifyCollectionChangedEventArgs
parameter defines two important properties,
OldItems
and NewItems
, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when
items are added, removed, relocated, or reset. To discover which of these actions triggered the event,
you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be
tested against any of the following members of the NotifyCollectionChangedAction
enumeration:
public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}
Solution 4
Explanation without Code
For those wanting an answer without any code behind it (boom-tish) with a story (to help you remember):
Normal Collections - No Notifications
Every now and then I go to NYC and my wife asks me to buy stuff. So I take a shopping list with me. The list has a lot of things on there like:
- Louis Vuitton handbag ($5000)
- Clive Christian’s Imperial Majesty Perfume ($215,000 )
- Gucci Sunglasses ($2000)
hahaha well I"m not buying that stuff. So I cross them off and remove them from the list and I add instead:
- 12 dozen Titleist golf balls.
- 12 lb bowling ball.
So I usually come home without the goods and she's never pleased. The thing is that she doesn't know about what i take off the list and what I add onto it; she gets no notifications.
The ObservableCollection - notifications when changes made
Now, whenever I remove something from the list: she get's a notification on her phone (i.e. sms / email etc)!
The observable collection works just the same way. If you add or remove something to or from it: someone is notified. And when they are notified, well then they call you and you'll get a ear-full. Of course the consequences are customisable via the event handler.
That sums it all up!
Solution 5
One of the biggest uses is that you can bind UI components to one, and they'll respond appropriately if the collection's contents change. For example, if you bind a ListView's ItemsSource to one, the ListView's contents will automatically update if you modify the collection.
EDIT: Here's some sample code from MSDN: http://msdn.microsoft.com/en-us/library/ms748365.aspx
In C#, hooking the ListBox to the collection could be as easy as
listBox.ItemsSource = NameListData;
though if you haven't hooked the list up as a static resource and defined NameItemTemplate you may want to override PersonName's ToString(). For example:
public override ToString()
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
Related videos on Youtube
![santosh singh](https://i.stack.imgur.com/ng43Y.jpg?s=256&g=1)
santosh singh
Just another developer in languages C#, SQL,Jest, Jquery 😊 https://www.codeguru.co.in Javascript testing using jest
Updated on November 07, 2020Comments
-
santosh singh over 3 years
What is the use of ObservableCollection in .net?
-
Sizons almost 9 years@TheMuffinMan true, yet I prefer the way things are explained on stackoverflow compared to MSDN's too rigid to formal way of explaining their own creations.
-
Chris Catignani over 3 yearsStill a good question 10 years later!
-
-
Kings over 9 yearsreally this happens ?? :O
-
dovid over 9 years
e.NewItems
&e.OldsItems
may be null depending on the action. It may throwNullReferenceException
. -
bohdan_trotsenko over 9 yearssidenote: when Action is Move, the moved element will appear in both NewItems and OldItems
-
BenKoshy over 6 yearswill the people_CollectionChanged event fire if i change the name of a Person in the in the collection (without altering the collection itself?)
-
SlowLearner about 6 yearsThank you for this: > WPF already has many operations like refreshing the UI built in so you get them for free when using ObservableCollections
-
Arie over 5 yearscan you explain why FooObservableCollection implemented collection? And why you ovverided InsertItem ?
-
abatishchev over 5 years@Arie: honestly, 8 years later I don't remember, so no idea. From what I see in the docs there is no need for any of this, it all should come out of the box.
-
Abhay Nagaraj over 3 yearsIt should fall into the
NotifyCollectionChangedAction.Replace
bucket, as the new value replaces the old value (unless, we reset the values to their defaults in the modification attempted). Although, I would be curious to know more about or what you referred to, by: "modifying an item in the collection without altering the collection itself"? Did you mean via an iterator, perhaps? -
BillW about 3 yearsChanging any Property or Field of the Observed Collection will not trigger CollectionChanged.