How List List <string> Object Adds Attached String
Someone please shed light on how the Add method is implemented for
(how the Add method is implemented for List in C #)
listobject.Add (); where List<User> listobject= new List<User>()is the ad for the object.
I know that with List we can do a lot of operations on the fly, and that too is type safe, but I am wondering how to implement the id add method so that it takes care of all this at runtime.
I hope that it does not copy the object and does not correct every addition, but I will restrain my fingers and wait for an answer :)
Using the Reflector , you can see exactly how this is implemented.
public void Add(T item)
{
if (this._size == this._items.Length)
{
this.EnsureCapacity(this._size + 1);
}
this._items[this._size++] = item;
this._version++;
}
"EnsureCapacity"...
private void EnsureCapacity(int min)
{
if (this._items.Length < min)
{
int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
if (num < min)
{
num = min;
}
this.Capacity = num;
}
}
, 'Capacity'
public int Capacity
{
get
{
return this._items.Length;
}
set
{
if (value != this._items.Length)
{
if (value < this._size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
}
if (value > 0)
{
T[] destinationArray = new T[value];
if (this._size > 0)
{
Array.Copy(this._items, 0, destinationArray, 0, this._size);
}
this._items = destinationArray;
}
else
{
this._items = List<T>._emptyArray;
}
}
}
}
List<T> . (List<string>) compile-time ( @Jason ), , .
, . . , string , , , .
string a = "a";
List<string> list = new List<string>();
list.Add(a); // now the item in the list and a refer to the same string instance
a = "b"; // a is now a completely new instance, the list
// is still referring the old one