Your original code does not work because of value types. You cannot do the following:
IEnumerable<int> ints = new[] { 1, 2 };
IEnumerable<object> os = ints;
so the compiler won't accept your definition since it can't guarantee that IEnumerable<TC>
is compatible with IEnumerable<T>
in general. If you add class
constraints to T
and TC
it compiles:
internal class ListIndexable<TC, T> : IIndexable<T> where TC : class, T where T : class
{
}
However, you can define ListIndexable
with only one type parameter instead of two. If you change your definition to:
internal class ListIndexable<T> : IIndexable<T>
{
private List<T> list;
public ListIndexable(List<T> list) { this.list = list; }
public T this[int i] { get { return list[i]; } }
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
}
then you can do:
IIndexable<IAnimal> animals = dogs.AsIIndexable();
where AsIndexable
can be defined simply as:
public static ListIndexable<T> AsIndexable<T>(this List<T> list)
{
return new ListIndexable<T>(list);
}