Does a Collection<T> wrap an IList<T> or enumerate over the IList<T>?
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 wha开发者_Go百科t 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.
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.)
According to Reflector - here is constructor of the Collection:
public Collection(IList<T> list)
{
if (list == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
this.items = list;
}
So as you can see Collection wraps IList and no data is copied.
精彩评论