Home
C#
Convert ArrayList to List
Updated Sep 3, 2022
Dot Net Perls
Convert ArrayList, List. In the C# programming language, an ArrayList can be converted into a List. This can be done in a variety of ways.
Convert ArrayList, Array
Conversion info. One conversion approach uses the extension method syntax. This syntax gives us an effective ToList method for the ArrayList type.
ArrayList
This program introduces the static Extensions class and the ToList generic method inside that class. ToList is a generic extension method—it has a type parameter.
Extension
Generic
Detail The "this" modifier is used on the ArrayList argument to specify that the method is an extension.
And Inside ToList, we allocate a List with the correct capacity, and then copy each element.
Detail We test the ToList method on an ArrayList instance. You can see that the method works correctly for the List of ints.
using System; using System.Collections; using System.Collections.Generic; static class Extensions { /// <summary> /// Convert ArrayList to List. /// </summary> public static List<T> ToList<T>(this ArrayList arrayList) { List<T> list = new List<T>(arrayList.Count); foreach (T instance in arrayList) { list.Add(instance); } return list; } } class Program { static void Main() { // Create ArrayList. ArrayList arrayList = new ArrayList(); arrayList.Add(1); arrayList.Add(2); arrayList.Add(3); // Use extension method. List<int> list = arrayList.ToList<int>(); foreach (int value in list) { Console.WriteLine(value); } } }
1 2 3
Notes, testing. I also tested the method using string literals in the ArrayList and it worked correctly. Just change the type of the local variables in the program.
String Literal
int
List
A summary. With ToList we converted an ArrayList to a List. Another approach is to convert the ArrayList to an Array, and then use the new List constructor with that Array as the parameter.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 3, 2022 (rewrite).
Home
Changes
© 2007-2025 Sam Allen