I am implementing IListSource that requires a method GetList() with the following signature:
IList GetList()
I am using .NET framework 2 and I’m wanting to return an object that implements IList as follows:
public System.Collections.IList GetList()
{
return this._mydata; // Implements IList<MyDataRow>
}
But I get a compile error saying: Cannot implicitly convert type MyData to System.Collections.IList.
If I create a new list of type List<MyDataRow>, populate it and return this list object, then it works. So in other words, this works:
public System.Collections.IList GetList()
{
List<MyDataRow> list = new List<MyDataRow>();
foreach (MyDataRow row in this._mydata)
{
list.Add(row);
}
return list;
}
But it seems very inefficient to have to recreate the list just to get it from type IList<T> to IList. Why is it that I can return a List<MyDataRow>' from 'GetList(), but not an IList<MyDataRow>? Does anyone know of a way for me to return the IList<MyDataRow> without repopulating a new list?
UPDATE:
The _mydata member variable is declared:
private MyData _mydata;
And MyData is declared:
public class MyData : IList<MyDataRow>
{
....
}
This is because
List<T>implementsIList,IList<T>cannot be cast toIListthey are 2 separate interfaces. So to answer your question:If the concrete type implements
IList(whichList<T>does) then you can explicitly cast it e.g.Update
Based on your update, you will have to update
MyDatato implementIListotherwise you have no choice but to return a new collection which does implement it.Alternatively, if
MyDatais indeed a generic list then I would suggest you have it inherit fromList<T>, that way you get a lot more flexibility & compatibility out of the box e.g.