Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a Collection<T> wrap an IList<T> or enumerate over the IList<T>?

Tags:

c#

If I am exposing a internal member via a Collection property via:

public Collection<T> Entries
{
    get { return new Collection<T>(this.fieldImplimentingIList<T>); }
}

When this property is called what happens? For example what happens when the following lines of code are called:

T test = instanceOfAbove.Entries[i];
instanceOfAbove[i] = valueOfTypeT;

It's clear that each time this property is called a new reference type is created but what acctually happens? Does it simply wrap the IList<T> underneath, does it enumerate over the IList<T> and to create a new Collection<T> instance? I'm concerned about performance if this property is used in a for loop.

like image 777
Brian Triplett Avatar asked Mar 12 '10 23:03

Brian Triplett


1 Answers

According to Reflector, the new Collection<T> just wraps the IList<T>:

public Collection(IList<T> list)
{
    if (list == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
    }
    this.items = list;
}

And from the docs:

Initializes a new instance of the Collection<(Of <(T>)>) class as a wrapper for the specified list.

(emphasis added)

So the overhead is minimal (the list is not enumerated), and changes to the returned collection will affect the original list.

(By the way, I am assuming you are referring to System.Collections.ObjectModel.Collection<T> -- there isn't a generic version of Collection in the top-level System.Collections namespace.)

like image 150
itowlson Avatar answered Sep 20 '22 12:09

itowlson