When using a delegate, is there a way to get an object response?

As an example:

WebClient.DownloadStringAsync (Uri) Method

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 e.Result trick?

+4
source share
5 answers
 wc.DownloadStringCompleted += (s, e) => { var result = e.Result; }; 

or if you like delegate syntax

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

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

 wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { // your code } 
+3
source

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)); } 
+3
source

Other answers use a lambda expression, but, for completeness, note that you can also specify delegate arguments:

 wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { // Use e.Result here. }; 
+3
source

Try the following:

 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)); } } 
+2
source

All Articles