1

I try to implement a PriorityQueue with C#:

public class PriorityQueue<T> : Heap<T> where T : IComparable<T> {
    ...
}

The Heap is abstract. I have MinHeap and MaxHeap that are derived from Heap.

public abstract class Heap<T> where T : IComp ...
public class MinHeap<T> : Heap<T> ...
public class MaxHeap<T> : Heap<T> ...

Is there a possibility to decide in the constructor of PriorityQueue during runtime, if the PrioQueue becomes a MinHeap or MaxHeap? Like:

public PriorityQueue(bool type) {
    if (type = smallestFirst) { this = MinHeap ... }
    else { this = MaxHeap ... }
}

If I try like this, then he says that "this" is writeprotected. Any other ideas?

2
  • Your example at the very end won't compile. You use one equals sign in the if statement – Cole Johnson Oct 19 '14 at 20:44
  • yes that is a standard mistake from me :D - but that mistakes I can find fast. I made it like Euphoric said. I just hoped I could do it a level higher, because actually the heap itself can be considered as a PriorityQueue. I was a bit surprised, that c# hasnt got so many useful generic datastructures. – Sneedlewoods Oct 19 '14 at 21:09
7

No, it is not possible.

You should be using composition instead of inheritance here. Have Heap<T> as field and assign specific instance into this field.

public class PriorityQueue<T> where T : IComparable<T> {
    Heap<T> _heap;

    public PriorityQueue(bool type) {
        if (type == smallestFirst) { _heap = new MinHeap<T>(); }
        else { _heap = new MaxHeap<T>(); }
     }
}
1

An alternative to Euphoric's suggestion is to use a Factory Method rather than calling new PriorityQueue directly, which is to say have a static method in PriorityQueue that decides which subtype to create and then returns an instance of the appropriate type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.