Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I try to implement a PriorityQueue with C#: public class PriorityQueue<T> : Heap

ID: 644880 • Letter: I

Question

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?

Explanation / Answer

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>(); }
}
}