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:
delegate
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?
e.Result
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; };
If you really want to use an anonymous delegate instead of lambda:
wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { // your code }
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)); }
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. };
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)); } }