Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is List.Clear() implemented in C#?

I assume it uses an array to implement List. How is List.Clear() implemented? Does it actually clean up the array or just make a new array for this list?

public class List {

    private Array _array;

    public void Clear1 () {
        _array.length = 0;
    }
    public void Clear2 () {
        _array = new Array();
    }
}
like image 685
Vicky Avatar asked Mar 18 '11 21:03

Vicky


People also ask

What does List clear do C#?

Removes all elements from the List<T>.

How do you clear an array in C#?

To empty an array in C#, use the Array Clear() method: The Array. Clear method in C# clears i.e.zeros out all elements.


2 Answers

Like this (using .NET Reflector):

public void Clear()
{
    if (this._size > 0)
    {
        Array.Clear(this._items, 0, this._size);
        this._size = 0;
    }
    this._version++;
}

As you see, it just clears the same array. It probably assumes that if you're reusing the same list, you'll probably want to refill it with roughly the same amount of data. If you want to release the array, you'll need to create a new List instance.

like image 102
StriplingWarrior Avatar answered Oct 12 '22 09:10

StriplingWarrior


MSDN:

Count is set to 0, and references to other objects from elements of the collection are also released.

Capacity remains unchanged. To reset the capacity of the List, call the TrimExcess method or set the Capacity property directly. Decreasing the capacity reallocates memory and copies all the elements in the List. Trimming an empty List sets the capacity of the List to the default capacity.

This method is an O(n) operation, where n is Count.

like image 36
T.K. Avatar answered Oct 12 '22 11:10

T.K.