0

I am implementing vivox in unity and I came across a situation in the tutorial where the guy has done something with AsyncCallback delegate that I want to confirm.

using UnityEngine;
using VivoxUnity;
using System;

public class VivoxLearn : MonoBehaviour
{
    VivoxUnity.Client client;
    ILoginSession loginSession;

private string issuer="";
private string tokenKey = "";
private string domain = "";
private Uri server=new Uri("");
private TimeSpan timespan = new TimeSpan(90);
private AsyncCallback loginCallback;              //check-1

private void Awake()
{
    client = new Client();
    client.Uninitialize();
    client.Initialize();
    DontDestroyOnLoad(this);
}
void Start()
{
    loginCallback = new AsyncCallback(Login_Result);      //check-2
}
public void Login(string username)
{
    AccountId accountId = new AccountId(issuer, username, domain);
    loginSession.BeginLogin(server, loginSession.GetLoginToken(tokenKey, timespan), loginCallback);//check-3
}

private void Login_Result(IAsyncResult ar)               //check-4
{
    try
    {
        loginSession.EndLogin(ar);
    }
    catch (Exception e)
    {

        Debug.Log(e.Message);
    }
}
}

In line check-3, instead of creating AsyncCallback delegate(check-1) and passing Login_Result (check-4) method to delegate(check-2), what if I directly pass Login_Result as the last argument in line (check-3)? Is that a legit and allowed way? If yes, then please explain a bit that why it is allowed to do so...

derHugo
  • 83,094
  • 9
  • 75
  • 115

1 Answers1

0

tl;dr

Yes, as long as it has the same signature

  • returns void
  • takes IAsyncResult as only parameter

-> AsyncCallback

It is basically simply

public delegate void AsyncCallback(IAsyncResult ar);

which basically equals using Action

Action<IAsyncResult>

except that using delegate you can give the parameters some meaningful names and XML documentation comment tags.

Both are basically just signature templates (very carefully said it is a little bit like interfaces and types). You can assign any method implementing the correct signature to them.


If you don't intend to somewhere store that delegate (like in your example in a field) then - as with any other value - it doesn't matter at all if you pass the callback method directly or via the delegate definition (see How to declare, instantiated and use a delegate)

loginCallback = new AsyncCallback(Login_Result);

is just the older way to write it. You can also simply do

loginCallback = Login_Result; 

and then it makes no difference if you first store this in a field or directly pass it to the method.

So you can also directly do

loginSession.BeginLogin(server, loginSession.GetLoginToken(tokenKey, timespan), new AsyncCallback(Login_Result);

or as said simply

loginSession.BeginLogin(server, loginSession.GetLoginToken(tokenKey, timespan), Login_Result); 
derHugo
  • 83,094
  • 9
  • 75
  • 115