views:

246

answers:

2

So I have a custom event like this:

    Work w = new worker()
    w.newStatus += new worker.status(addStatus);
    w.doWork();

    void addStatus(string status)
    {
     MessageBox.Show(status);
    }

and this:

    public event status newStatus;
    public delegate void status(string status);

    public void doWork()
    {
        newStatus("Work Done");    
    }

If I were to make "addStatus" an overload, what would I have to do to pass overload parameters without creating a second delegate/event?

A: 
    void addStatus(string status, int something)
or
    void addStatus(int status)
or
    void addStatus()
should all work.
Rohith
+2  A: 

Make your status delegate generic like this:

public event Status<String> NewStatus;
public event Status<Int32> OtherStatus;
public delegate void Status<T>(T status);

public void DoWork()
{
    NewStatus("Work Done");
    OtherStatus(42);
}

Then you can create strongly typed events that use the same delegate.

Edit: Here is a complete example showing this in action:

using System;

class Example
{
    static void Main()
    {
        Work w = new Work();
        w.NewStatus += addStatus;
        w.OtherStatus += addStatus;
        w.DoWork();
    }    
    static void addStatus(String status)
    {
        Console.WriteLine(status);
    }
    static void addStatus(Int32 status)
    {
        Console.WriteLine(status);
    }
}

class Work
{
    public event Status<String> NewStatus;
    public event Status<Int32> OtherStatus;
    public delegate void Status<T>(T status);

    public void DoWork()
    {
        NewStatus("Work Done");
        OtherStatus(42);
    }
}
Andrew Hare
I was initially confused why you were suggesting he use generics. Then I reread the OP's question carefully and saw that "what would I have to make a second custom event" can be understood two ways. You interpreted it as "what would I have to do to *avoid making a second delegate* " and gave a great answer to that question. I suggest you extend your answer to make it clear that you would use a generic delegate if you didn't want two separate delegate types, but that you could just as easily use two delegates and not use generics. (So others won't be confused as I was at first)
Ray Burns
That's the same thing I was doing, I just wanted to know if there was a way to pass overload parameters over an event.
Lienau
If both events have the same number of parameters you can share the delegate by making it generic. If the events need to pass different numbers of parameters you will need to use separate delegates.
Andrew Hare
Alright, Thanks Andrew.
Lienau