tags:

views:

61

answers:

1

Lets say I have 2 class types TEmployee (with properties A,B) and TDept (with properties C,D). Then I make a class descended from TList like so :

TMyCcontainer<T>=class(TList<T>)

So I can create instances of TMyCcontainer and fill with TEmployee or TDept. In my TMyCcontainer class is there anyway to access properties A,B of TEmployee, or properties C,D of TDept?

Of course the type is generic so it would appear not. And this is the problem I always have with generics - maybe I am mis-using them. I recently learnt abaout constraints, and thought I had found out what I had been missing....

So I created 2 interfaces say IEmployee and IDept, made my 2 orig class es to be interfaceobjects, and put in my contraint on my Tlist ie

TMyCcontainer<T:IEmployee,IDept>=class(TList<T>)

Of course I was quickly disappointed as this is saying you must implement BOTH of these interfaces in any type I put in my generic TList (TMyContainer), whereas I just want ONE in any particular instance, then ther other in another instance. I would have to implement both IEmployee and IDept in my TDept class which is not what I want obv.

Is there any good way to access members of a Type within a generic container? Or should I not be using generics to do this type of thing. Ty

+3  A: 

All generic constraints you put on a class have to be fulfilled by the generic type. Looks like what you're really looking for is two different generic types: TMyContainer<TDept> and TMyContainer<TEmployee>. Then you'll have access to all the properties of those types, individually.

Mason Wheeler
Ty Mason. I have been doing something completely stupid - trying to put code into TMyContainer and get somehow access to properties in there although the type of T is not known. I beleive I should create another class descended from TMyContainer for each known type I want put in TMyContainer, thus enabling me to access type properties and maintain encapsulation of my code at the same time.
csharpdefector
@Csharpdefector: Yeah, exactly.
Mason Wheeler