Skip to content

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

Updated: at 02:12 PM

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;
                                <span class="kwrd">if</span> (c == <span class="kwrd">null</span>)
                                {
                                    WriteLine(<span class="str">&quot;xxx No conference data downloaded, skipping&quot;</span>);
                                }
                                <span class="kwrd">else</span>
                                {
                                    <span class="kwrd">if</span> (SaveToDatabase(c))
                                    {
                                        ea.Success = <span class="kwrd">true</span>;
                                    }
                                }
                                UpdateFinished(<span class="kwrd">null</span>, ea);
                                isUpdating = <span class="kwrd">false</span>;
                            }
);</pre>

 

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.

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects