Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Casting objects that inherit from List<T>

Status
Not open for further replies.

LFCfan

Programmer
Nov 29, 2002
3,015
GB
I have a class Workers as below

Code:
public class Workers : List<Worker>
{
    public static Workers GetAll()
    {
        WorkersReader reader = new WorkersReader();
        -- return (Workers)reader.ExecuteReader();

        List<Worker> workerlist = reader.ExecuteReader();
        Workers workers = new Workers();

        foreach (Worker w in workerlist)
        {
            workers.Add(w);
        }
        return workers;
    }
}
Now reader.ExecuteReader() returns a List<Worker> , and as you can see in the line commented out above, I initially thought I could explicitly cast the List<Worker> as a Workers object.

I can see why I am unable to cast List<Worker> to Workers (one can cast a Workers object to a List<Worker> but not the other way round, much like (Fruit)Apple is valid but (Apple)Fruit isn't, in the case of class Apple:Fruit{})

In order to get round this I've had to loop through each of the Worker objects in the List<> and add them to a Workers object, and then return the Workers object.

While this works fine (presumably adding a bit of an overhead), is there a more elegant way I could accomplish this? I'm stumped.

Many thanks for any pointers

~LFCfan

 
what you do gain by having Workers inherit List<Worker>()?

if you need/want the Workers super class
Code:
public class Workers : List<Worker>
{
    public class Workers(IEnumerable<Worker> workers)
         : base(workers)
    {
    }

    public static Workers GetAll()
    {
        WorkersReader reader = new WorkersReader();
        return new Workers(reader.ExecuteReader());
    }
}

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Thanks Jason
I ended up inheriting from Collection<T> instead.

As for what I gain by inheriting from List<T> I'm not entirely sure yet :)

~LFCfan

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top