What is the usage of ArrayList in C#?

In C#, an ArrayList is a dynamic array that can store objects of different types and can adjust its size dynamically. ArrayList provides many methods to operate and access elements in the array.

Here are some common methods and uses of ArrayList:

  1. Instantiate an ArrayList object.
  2. Create a new ArrayList called ‘list’.
  3. Add elements:
  4. list.Add(1); // Add an integer
    list.Add(“Hello”); // Add a string
    list.Add(true); // Add a boolean
  5. Access Elements
  6. Retrieve the element at index 0 from the list.
  7. Remove items:
  8. list.Remove(1); // Remove specified element
    list.RemoveAt(0); // Remove element at specified index
  9. Fetch the number of elements:
  10. Assign the total number of elements in the list to the variable “count”.
  11. Check if the element exists.
  12. Check whether the element exists in the list.
  13. Clear the ArrayList.
  14. Clear the list.
  15. Iterate through an ArrayList.
  16. For each element in the list, print it to the console.

It is important to note that due to ArrayList being able to store objects of different types, type casting is required when using it. In addition, C# also provides a more type-safe generic collection class List, which is recommended to be used instead of ArrayList in new code.

bannerAds