I did not know that it is possible to have a delegate as a call to a method, then have that method actually execute that delegate at it’s convenience. I’m busy converting a Xamarin conference application for the IPad and am wrangling getting it to show Silicon Valley Code Camp data rather than MWC (Mobile World Conference data).
So, here is the method I ran into:
var siteParser = new MWC.SAL.MWCSiteParser(); siteParser.GetConference (Constants.ConferenceDataUrl, () => { var c = siteParser.ConferenceData; if (c == null) { WriteLine("xxx No conference data downloaded, skipping"); } else { if (SaveToDatabase(c)) { ea.Success = true; } } UpdateFinished(null, ea); isUpdating = false; } );
And the method that calls it:
public void GetConference (string url, Action action) { var webClient = new WebClient (); Debug.WriteLine ("Get remote data for conference"); webClient.DownloadStringCompleted += (sender, e) => { try { var r = e.Result; ConferenceData = DeserializeConference (r); } catch (Exception ex) { Debug.WriteLine ("ERROR deserializing downloaded conference XML: " + ex); } action(); }; webClient.Encoding = System.Text.Encoding.UTF8; webClient.DownloadStringAsync (new Uri (url)); }
I noticed the “action();” call and could not figure out where that was coming from until I noticed it was the second paramter of GetConference(). Then, I looked at the call (first chunk of code) and there was a delegate!
Very cool. I feel like I should have know this but none the less, I do know.






very powerful concept, internalizing that a delegate is just a function variable and that lamdas are just anonymous delegates
Yeah, you should have a look at continuations, or even have a look into Reactive Extensions (Rx) -> which are like IEnumerable, but you specify the delegate of what to execute up front.
This gives you push based collections. They make handling async streams of data trivial. It also gives you the capability of making workflows of data composable, and because you’re handling pipelines of data, (and are not blocking) your code can be incredibly performant.
you can improve the readability by passing conferencedata as a parameter to the delegate.