4

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?

balexandre
  • 73,608
  • 45
  • 233
  • 342

5 Answers5

3
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;
            };
PHeiberg
  • 29,411
  • 6
  • 59
  • 81
3

If you really want to use an anonymous delegate instead of lambda:

wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
{
    // your code
}
Snowbear
  • 16,924
  • 3
  • 43
  • 67
3

You should be able to use the following:

using (WebClient wc = new WebClient())
{
    wc.DownloadStringCompleted += (s, e) =>
        {
            string fileContent = (string)e.Result;
        };
    wc.DownloadStringAsync(new Uri(fileUrl));
}
ChrisF
  • 134,786
  • 31
  • 255
  • 325
3

The other answers use a lambda expression but, for completeness, note that you can also specify the delegate's arguments:

wc.DownloadStringCompleted += 
    delegate(object sender, DownloadStringCompletedEventArgs e) {
        // Use e.Result here.
    };
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
2

Try this:

public void GetFile(string fileUrl)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadStringCompleted += 
            (s, e) => {
                // Now you have access to `e.Result` here.
            };
        wc.DownloadStringAsync(new Uri(fileUrl));
    }
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172