In C# Passing Delegate As Parameter, Then Executing on Return

Posted by Peter Kellner on August 30, 2012 · 3 mins read

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.