I’m working with some code that I’ve found online and I don’t quite understand delegates yet. I read some articles about it but the examples I’ve seen are much more simplistic and not very similar. This is the code I’m having trouble with:
var cb = new Action<OAuthAccessToken, TwitterResponse>(CallBackVerifiedResponse);
service.GetAccessToken(_requestToken, pinText.Text, CallBackVerifiedResponse);
Is the new Action object actually executing the CallBackVerifiedResponse method or does that only happen in the second line? OAuthAccessToken and TwitterResponse are the types of the parameters that the CallBackVerifiedResponse method asks for but to me it doesn’t look like they’re initialized at any point.
Can someone offer me an explanation or an alternative/more simpel way to write those two lines? Here’s the full method just in case:
void CallBackVerifiedResponse(OAuthAccessToken at, TwitterResponse response)
{
if (at != null)
{
SerializeHelper.SaveSetting<TwitterAccess>("TwitterAccess", new TwitterAccess
{
AccessToken = at.Token,
AccessTokenSecret = at.TokenSecret,
ScreenName = at.ScreenName,
UserId = at.UserId.ToString()
});
}
}
Neither. The code inside
GetAccessTokenwill call theCallBackVerifiedResponsemethod at some point. Or not. Depends on the code inGetAccessToken. I asssume it’ll call it when the response has been verified.Basically, a delegate is a way to hand someone a function and say “Make this function call later, when you need it”.
OAuthAccessTokenandTwitterResponseare initialized withinGetAccessToken. That’s the goal ofGetAccessToken– to asynchronously get you anOAuthAccessTokenand tell you about it when it’s done. The purpose of the delegate is to provide the API with a mechanism to do that.