Search code examples
c#delegatesanonymous-methods

When using a delegate, is there a way to get hold of the object response?


As an example:

WebClient.DownloadStringAsync Method (Uri)

Normal code:

private void wcDownloadStringCompleted( 
    object sender, DownloadStringCompletedEventArgs e)
{ 
    // The result is in e.Result
    string fileContent = (string)e.Result;
}

public void GetFile(string fileUrl)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadStringCompleted += 
             new DownloadStringCompletedEventHandler(wcDownloadStringCompleted);
        wc.DownloadStringAsync(new Uri(fileUrl));
    }
}

But if we use an anonymous delegate like:

public void GetFile(string fileUrl)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadStringCompleted += 
            delegate {
                // How do I get the hold of e.Result here?
            };
        wc.DownloadStringAsync(new Uri(fileUrl));
    }
}

How do I get the hold of e.Result there?


Solution

  • wc.DownloadStringCompleted += 
                (s, e) => {
                    var result = e.Result;
                };
    

    or if you like the delegate syntax

    wc.DownloadStringCompleted += 
                delegate(object s, DownloadStringCompletedEventArgs e) {
                    var result = e.Result;
                };