Alex Rivera | Logout

Remove all All Elements not working

Asked 2011-11-08T15:27:39.820
12

I noticed this function in a .NET project I am working on.

    private static void RemoveAllElements(ref List<int> listToBeRemoved)
    {
        foreach (var i in listToBeRemoved)
        {
            listToBeRemoved.Remove(i);
        }
    }

Is this the quickest way to remove all elements from a list? I also noticed this function doesn't catch any exceptions. Should I change this? This is in existing code.

Edit
Report

1 Answer

8
list.Clear()

See the documentation: http://msdn.microsoft.com/en-us/library/dwb5h52a.aspx

Changing the collection that you are enumerating makes the enumerator invalid, so this is very bad practice. See the remarks on List.GetEnumerator:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

The Clear method itself will not throw an exception, but if listToBeRemoved is null, you will get a NullReferenceException.

answered 2011-11-08T15:29:45.727

Your Answer