Search code examples
c#listobservablecollection

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);

Solution

  • 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.