1

Possible Duplicate:
Observable Stack and Queue

I have a stack<String> in my application. I can use Stack.Push(Object) and Stack.Pop(). But I would like to know whenever a new object is added in the Stack. I don't know even if it is possible or not. Any suggestions?

Community
  • 1
  • 1
s.k.paul
  • 7,099
  • 28
  • 93
  • 168

1 Answers1

4

Create class that inherits from Stack:

class StackHolder: Stack
{

    public delegate void ItemAddedDelegate(object item);
    public event ItemAddedDelegate ItemAdded;

    public override void Push(object obj)
    {
        base.Push(obj);
        if (ItemAdded != null)
        {
            ItemAdded(obj);
        }
    }
}

And here is how you should use it:

        StackHolder sh = new StackHolder();
        sh.ItemAdded += new StackHolder.ItemAddedDelegate(sh_ItemAdded);

Here is handler for event:

    void sh_ItemAdded(object item)
    {
       //TODO: handle event
    }
Gregor Primar
  • 6,759
  • 2
  • 33
  • 46
  • You're no following the event pattern. You should use `(object sender, EventArgs e)` – Amiram Korach Nov 29 '12 at 16:04
  • Yes this is true. My intention was just to show op the possible concept. In this case EventArgs are not required at all. – Gregor Primar Nov 29 '12 at 16:06
  • 2
    He is talking about generic Stack<> class - it seems. Generic Stack<>'s Push and Pop are not virtual. – Igor Nov 29 '12 at 16:10
  • Do you agree that everything Pushed to StackHolder can be presented as string? This is the fastest and easiest way to do it. Ofcourse you can create class that will hold Stack and support ItemAdded event, but then more code is required. – Gregor Primar Nov 29 '12 at 16:20
  • 3
    I think it is better to create a class `StackHolder` with `Stack` inside. – Igor Nov 29 '12 at 16:24
  • Yes this would be the cleanest solution but more time consuming for development :) – Gregor Primar Nov 29 '12 at 16:27
  • @Primar - Thanks. May i use this same concept for "Queue" class ? – s.k.paul Nov 29 '12 at 16:38