Xamarin Tips and Tricks – Clearing Lists in C#

(Originally published 4/3/17)

Sometimes, using the built-in Clear() function on C# Lists may not always work. For example, I needed to clear a list of all its contents every time I returned to a Page view. Using the Clear() function was not clearing the list properly and thus resulting in the Page crashing. Although it may not always be the most obvious solution, if you are every getting IndexOutOfBounds exceptions when dealing with clearing a list, you may want to try doing it the old fashioned way – using a for-loop to traverse the List from head to tail and using the RemoveAt function to remove the object. Here is a snippet of the function below:


public void ClearList(List myList)
{
for(int x = myList.Count 1; x >= 0; x)
{
myList.RemoveAt(x);
}
}

view raw

ClearList.cs

hosted with ❤ by GitHub

This simple function can solve some major issues regarding clearing of a list. This can really be applied to any language in any situation where the built in clear function is not doing the proper job. Thanks for reading, and stay tuned for more updates.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s