anderhil anderhil - 7 days ago 6
C# Question

ObservableCollection<> vs. List<>

I have lots of entities with nested

List<>
in each.

For example, I have
BaseEntity
which has
List<ColumnEntity>
.
ColumnEntity
class has
List<Info>
and so on.

We are working with a WPF UI, and we need to track all changes in every List of
BaseEntity
. It is implemented by instantiating a
new ObservableCollection
based on the needed list, and with binding to that
ObservableCollection
.

What are the pros and cons changing all these nested
Lists
to
ObservableCollections
? So we can track all changes in
BaseEntity
itself without reassigning each list of
BaseEntity
to modified bound
ObservableCollection
?

Assuming that methods specific to
List
are never used.

Answer

Interesting question, considering that both List and ObservableCollection implement IList<T> there isn't much of a difference there, ObservableCollection also implements INotifyCollectionChanged interface, which allows WPF to bind to it.

One of the main differences is that ObservableCollection does not have AddRange method, which might have some implications.

Also I would not use ObservableCollection for places where I know I would not be binding to, for this reason it is important to go over your design and making sure that you are taking the correct approach in separating layers of concern.

As far as the differences between Collection<T> and List<T> you can have a look here Generic Lists vs Collection

Comments