Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
N

NT986

@NT986
About
Posts
1
Topics
1
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • Generics return type cannot cast.
    N NT986

    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.

    C# database help question lounge
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups