I cannot get generics to return a type that it does not know is correct. I have a collection of general objects each with a sorted keyfield ID cTypeA 2 cTypeB 3 cTypeA 7 cTypeA 9 cTypeB 12 in one ArrayList, all of which derive from cType. I want to create a separate list of ID references using generics, but which returns the actual objects in an indexer. That way I am assured of type safety when using the object (displaying in a listview say) rather than casting at the end use point:
public class cList<T>
{
public cList(cIDList UseOwner)
{
Owner = UseOwner;
ListItems = new ArrayList();
}
public T this\[int Index\]
{
get
{
if ((Index >= 0) && (Index < ListItems.Count))
{ return (T) Owner.GetObject((int)ListItems\[Index\]); //\*\*\*problem cannot implicitely convert to type T
}
}
}
private cIDList Owner;
private ArrayList ListItems; //would contain 2,7,9
}
to implement this
cList<cTypeA> AItem = new cList<cTypeA>(MyIDList);
(assume items added)
cTypeA UseA = AItem[2];
Is there a way to solve this problem? The only way I can see is to do the above without generics, copy and paste then change the return cast type for what I use now, and in the future. Not easily manageable! Thanks.