using System.Collections;
using System.Collections.Generic;
public static void Main()
var results = new List<object>();
var l = new ListWrapper();
Console.WriteLine("Call via foreach direct");
Console.WriteLine("Call via LINQ direct");
results.AddRange(l.Select(o => o));
Console.WriteLine("Call via foreach interface");
Console.WriteLine("Call via LINQ interface");
results.AddRange(li.Select(o => o));
public class ListWrapper : IEnumerable<object>, IList<object>
List<object> _list = new List<object>() { "1", "2", "3" };
public List<object>.Enumerator GetEnumerator()
Console.WriteLine("direct method call (no boxing)");
return _list.GetEnumerator();
IEnumerator<object> IEnumerable<object>.GetEnumerator()
Console.WriteLine("interface call (with boxing)");
return ((IEnumerable<object>)_list).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
Console.WriteLine("interface call (with boxing)");
return ((IEnumerable<object>)_list).GetEnumerator();
public object this[int index] { get => ((IList<object>)_list)[index]; set => ((IList<object>)_list)[index] = value; }
public int Count => ((IList<object>)_list).Count;
public bool IsReadOnly => ((IList<object>)_list).IsReadOnly;
public void Add(object item)
((IList<object>)_list).Add(item);
((IList<object>)_list).Clear();
public bool Contains(object item)
return ((IList<object>)_list).Contains(item);
public void CopyTo(object[] array, int arrayIndex)
((IList<object>)_list).CopyTo(array, arrayIndex);
public int IndexOf(object item)
return ((IList<object>)_list).IndexOf(item);
public void Insert(int index, object item)
((IList<object>)_list).Insert(index, item);
public bool Remove(object item)
return ((IList<object>)_list).Remove(item);
public void RemoveAt(int index)
((IList<object>)_list).RemoveAt(index);