Custom Collection and Inherited Class Types

1046 views c#

I'm having difficulty, probably missing something simple, with queuing and unqueuing items in a collection.

I have classes with various levels of inheritance:

public abstract class Item
{  //stuff }

public class DetailItem : Item
{  //stuff }

public class SuperDetailItem : DetailItem
{  //stuff }

public class OddItem : Item
{  //stuff }

I then have a ConcurrentQueue<T> like so:

public class CQItems<Item> : ConcurrentQueue<Item>
{  //some methods }

One of the methods adds items when called, so I do something like:

CQItems<Item> items = new CQItems<Item>();

It'll create i items in the queue. This works, though currently in the method I am specifying creating DetailItem items - I'd like to have that be dynamic if possible as well, but that'll be a different question. So later, I call to get a DetailItem out like so:

 DetailItem item;

 items.TryDequeue(out item);

and get the message "Cannot convert from DetailItem to Item".

I don't want to make a specific collection for each inherited type. What piece am I missing? Thanks!

answered question

1 Answer


Firstly you create a queue which is supposed to store Item elements.

CQItems<Item> items = new CQItems<Item>();

Then you say: take whatever concrete type deriving from Item you have and assign it to DetailItem variable:

DetailItem item;
items.TryDequeue(out item);

TryDequeue "returns" an Item via out modifier. This is basically the same thing as if you tried to assign an Item to a DetailedItem like so:

Item item = GetItem();
DetailedItem detailedItem = item; // compilation error

Which obviously makes no sense.

The "Try" part in TryDequeue corresponds to the empty queue, not to the casting.

posted this

Have an answer?


Please login first before posting an answer.