(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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ClearList(List myList) | |
{ | |
for(int x = myList.Count – 1; x >= 0; x—) | |
{ | |
myList.RemoveAt(x); | |
} | |
} |
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.