views:

63

answers:

3

I wish to create a custom EventHandler that can have any number of objects as its parameters and the objects it gets isn't known in advance.

I know I can pass it an Object[] but what I would like is something similar to

MyEventHandler someCustomEvent(Object obj1, Object obj2, Object obj3)

where the number of objects can be 0 or 10 if needed.

EDIT:

So thanks to the comments and answers I've got I've come to this,

public class FinishedEventArgs : EventArgs {
            public Object[] Args{ get; set; }
        }

protected void OnFinished(params Object[] args) {
            if(this.Finished != null) {
                this.Finished(this, new FinishedEventArgs() {
                    Args = args
                });
            }
        }

Does it look acceptable?

+3  A: 

You can define a delegate as such:

public delegate void MyHandler(object p1, object p2, object p3);

and then use it in your event definition:

public event MyHandler MyEvent;

However, this is contrary to best practices and not recommended. Instead, you should encapsulate all the extra information you require into your own EventArgs subclass and use that from your delegate:

public class MyEventArgs : EventArgs
{
    // any extra info you need can be defined as properties in this class
}

public event EventHandler<MyEventArgs> MyEvent;

HTH,
Kent

Kent Boogaart
Thank you Kent. Maybe I was a bit unclear in what I actually wanted. I would like to be able to pass either an array of objects or several objects individually and I don't know how many objects there are in advance.
Jova
+1  A: 

There's nothing to stop you declaring a delegate that accepts a params array, the same as you would define any other method which takes multiple arguments:

delegate void someCustomEvent(params object[] args);

event someCustomEvent sce;

However, it would be unusual. As Kent says, it's more normal to follow the convention on the .Net platform of having event handlers accepting two arguments, the sender (object), and the event arguments (EventArgs, or something deriving from it).

Damien_The_Unbeliever
+6  A: 

EventHandler is just a delegate.

You can create delegate like this:

public delegate void Foo(params object[] args);

And event:

public event Foo Bar;

You will end up with firing event like this:

Bar(1, "");

But, as @Kent Boogaart said, you should create events using EventHandler<TEventArgs>, so better approach would be creating class:

public class MyEventArgs : EventArgs
{
    public MyEventArgs(params object[] args)
    {
        Args = args;
    }

    public object[] Args { get; set; }
}

And event:

public event EventHandler<MyEventArgs> Bar2;

So you will fire event like this:

Bar2(this, new MyEventArgs(1, ""));
prostynick
Thank you for your answer, it sums up everything I was looking for pretty well.
Jova