C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
This: 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 simply copy each element.
Main: We test the ToList method on an ArrayList instance. You can see that the method works correctly for the List of ints.
C# program that converts ArrayList to List
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);
}
}
}
Output
1
2
3