Best alternative to Queue<T>

I made Queue. Queue was nice until I came across a reason to encapsulate a different type than Queue was written for.

I know that I can’t rewrite it as the generic Queue

What are some ways you guys work around this?

It really depends on what you’re trying to achieve.

If you’re after type safety, you can create a queue wrapper class that takes a System.Type object as a parameter and validates calls to Enqueue. Then you’ll only need one class.

class MyQueue {
    private Queue queue = new Queue();
    private Type type;

    MyQueue(Type type) => this.type = type;

    public void Enqueue(object o) {
        if (o.GetType() != this.type) throw new ArgumentException("Wrong type");

        this.queue.Enqueue(o);
    }
}

If you want strongly typed methods, you’ll have to create a new queue per type (which is what generics does behind the scenes when it instantiates a type).

class MyQueue {
    private Queue queue = new Queue();

    public void Enqueue(int o) => this.queue.Enqueue(o);
    public int Dequeue() => (int)this.queue.Dequeue();
}
1 Like

Thank you for the examples.

I am not going after Type Safety. And I was hoping to avoid (explicitly) defining Strongly Typed methods.

My goal was to write less code :slight_smile:

And the second option seems pretty good in helping me there.