tags:

views:

148

answers:

5

Somebody please shed some light on how Add method is implemented for

(how Add method is implemented for List in c#)

listobject.Add(); where List<User> listobject= new List<User>() is the declaration for the object.

I know that using List we can perform many operations on a fly and that too with type safety, but what I wonder is how id add method implemented so that it takes care of all that at run time.

Hope it doesnot copy the object and make adjustment on each add but I will keep my fingers crossed and wait for your reply :)

+1  A: 

No it will work on the string reference, otherwise there wouldn't be much point in using it if it always cloned you're objects.

You can actually check this sort of thing within Visual Studio by using the memory screens, it's possible to compare the address of the added item, and the original and you'll see that they point to the same memory location.

Ian
+1, although not quite eloquent, what Ian is saying is true. There would be a serious overhead issue if it was making copies all the time.
acron
@Ian, I think I have not been able to explain properly, string is just for example I want to know how List manage items of the the type T in List<T>,how Add method increases the size of the list(by copying and to a list of greater size or something).
Vinay Pandey
Don't quite understand why I got downvoted?
Ian
A: 

For a List, the Add method will be of generic type T, in this case a string. The content of the list will be a reference to the original variable, so if you modify the string in the list it will modify the original and vice versa.

Antony Koch
+3  A: 

Internally the List<T> holds the items in an array. The actual implementation (List<string>) is created at compile-time runtime (thanks @Jason for the correction), so internally there will be a string array that holds the items.

For reference types the list will hold a reference to the same object instance that you added. This is true for strings as well. However, note that the string class is immutable, so any time you modify a string, it actually results in a new instance.

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
Fredrik Mörk
@Fredik Mörk: Actually, it's done at runtime by the CLR. Basically, the compiler just spits out IL and metadata that says "I'm going to be using the generic type `List<T>` with type parameter `string`." At runtime, the CLR checks to see `List<string>` has been compiled to native code. If it hasn't, the JITter will take the IL for `List<T>` and the type parameter `string` and spit out a native implementation of `List<string>`. The nice thing is that for reference types the JITter can reuse the code (it's just pointers under the hood). Value types each get their own version.
Jason
@Jason: thanks for the correction; you are right of course (I updated the answer).
Fredrik Mörk
Plus one from me by the way. :-)
Jason
+1  A: 

As Frederik notes, List uses an array internally. It creates the array with an initial size and as more items are added, if the array is filled to capacity, it is copied into a larger array. That is why if you know ahead of time that a List will contain many strings, it can help to specify its initial capacity in the constructor.

When you remove items from the list, or insert in the middle, it must shift all the elements in the internal array so a List is not particularly optimized for adding/removing many items. You may be better off using a LinkedList which is much more efficient at add/remove operations but gives up the ability to efficiently access elements in the list by position.

Different collections have different implementations that are best suited for certain scenarios. For a good example of how various collections are implemented, I suggest checking out PowerCollections library that was released by Wintellect. Many of the collections are no longer relevant in .NET 3.5/4.0 but they provide some great insight on how to go about implementing collections.

Josh Einstein
+4  A: 

Using Reflector you can see exactly how its implemented.

public void Add(T item)
{
    if (this._size == this._items.Length)
    {
        this.EnsureCapacity(this._size + 1);
    }
    this._items[this._size++] = item;
    this._version++;
}

Following '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;
    }
}

And finally the setter for '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;
            }
        }
    }
}
bic
@bibcot, thank you for your response.
Vinay Pandey
bitcot, you do realise if you're going to post that you most likely need to include a copyright notice?
Ian
@Ian, can you elaborate on that? Are you referring to Reflector output or the .Net framework code? I've gone over the license for Reflector http://www.red-gate.com/products/reflector/license.htm and cant seem to find anything, albeit my legalese is not the best :-)
bic
.Net framework code, I'm fairly sure it's got a copy right licence on it no?
Ian
Hmm, the .Net source code is licensed under the 'Microsoft Reference Source License'. http://en.wikipedia.org/wiki/Shared_source#Microsoft_Reference_Source_License_.28Ms-RSL.29 I've no idea now if I should just delete my answer. Does anyone else know more about this?
bic