Jesse
Jesse

Reputation: 599

C# Pass a delegate as an argument

I am aware I can do this:

WebClient client = new WebClient();
client.UploadStringCompleted += delegate(object sender, UploadStringCompletedEventArgs e)
{
    //handle event
};
client.UploadStringAsync(myURI, "POST", "some_data");

But is there a way I can pass an inline delegate as an argument? Something like this:

DoRequest("some_data",
    delegate(object sender, UploadStringCompletedEventArgs e)
    {
        //handle event
    });

public void DoRequest(string data, UploadStringCompletedEventHandler event)
{
    WebClient client = new WebClient();
    client.UploadStringCompleted += event;
    client.UploadStringAsync(myURI, "POST", data);
}

Upvotes: 1

Views: 512

Answers (2)

Richard Anthony Hein
Richard Anthony Hein

Reputation: 10650

Yes, that code is correct, except you can't call your parameter event. I'd also use a lambda expression instead because it's nicer.

DoRequest("some_data", (o, e) => {/* handle event */});

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 838006

Yes, you can write exactly that except that event is a keyword and can't be used as a variable name.

Upvotes: 2

Related Questions