Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize length of ObservableCollection<T> the way you initialize a List<T>

Is there any way to initialize the capacity of an ObservableCollection<T> like you can a List<T>?

For example:

var observableCollection = new ObservableCollection<int>(100);
like image 326
declouet Avatar asked Apr 14 '14 20:04

declouet


2 Answers

No there is not. One of the constructors for ObservableCollection<T> takes a List<T>, so you might think you can do this:

new ObservableCollection<int>(new List<int>(100));

But that doesn't work. Internally, ObservableCollection copies the list and doesn't take into account any capacity properties on the list. You can verify this by looking at the constructors using .NET Reflector.

like image 104
Michael Gunter Avatar answered Nov 14 '22 23:11

Michael Gunter


This is an old question. But, I thought it might be worthwhile to know that currently, it is possible to set the backing List capacity at the risk of relying on the internal implementation.

The Items property that is exposed by the base Collection<T> class is currently implemented as a List<T>. With type casting, you can set that property's Capacity.

Note that this does rely on the current implementation of both the List<T> and ObservableCollection<T> classes. If it is critical that you be able to set the backing Capacity and not worry that the .NET implementation will change (for instance, changing the backing list to a Dictionary or HashSet), you should instead create a new class that implements your needed interfaces.

You can use the Microsoft Reference Source as well as .NET Reflector.

like image 36
Martin Soles Avatar answered Nov 14 '22 21:11

Martin Soles