Why does the following DisplayContents not work(wont compile) for an ArrayList as it inherits form IEnumerable)
public class Program
{
static void Main(string[] args)
{
List<int> l = new List<int>(){1,2,3};
DisplayContents(l);
string[] l2 = new string[] {"ss", "ee"};
DisplayContents(l2);
ArrayList l3 = new ArrayList() { "ss", "ee" };
DisplayContents < ArrayList>(l3);
Console.ReadLine();
}
public static void DisplayContents<T>(IEnumerable<T> collection)
{
foreach (var _item in collection)
{
Console.WriteLine(_item);
}
}
}
ArrayListimplementsIEnumerable, but not the genericIEnumerable<T>. This is to be expected, sinceArrayListis neither generic nor bound to any specific type.You need to change the parameter type of your
DisplayContentsmethod fromIEnumerable<T>toIEnumerableand remove its type parameter. The items of your collection are passed toConsole.WriteLine, which can accept anyobject.