Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Create an EventHandler that can take any number of parameters

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?

like image 584
Johan Alkstål Avatar asked Oct 22 '10 07:10

Johan Alkstål


2 Answers

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, ""));
like image 174
prostynick Avatar answered Oct 12 '22 19:10

prostynick


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;
like image 21
Kent Boogaart Avatar answered Oct 12 '22 18:10

Kent Boogaart