Offir
Offir

Reputation: 3491

Pass a void function as a parameter with two arguments

I want to pass to SetTimer the function TagContactByMail instead of 2 strings.

 public void AddTagToContact(string tagName, string contactEmail)
        {
                SetTimer(tagName, contactEmail);
                aTimer.Dispose();
        }

This is the function I want to pass as a parameter to SetTimer.

private void TagContactByMail(string contactEmail, string tagName)
    {
        //Stop timer.
        aTimer.Stop();

        //If the time passed or we successfuly tagged the user. 
        if (elapsedTime > totalTime || tagSuccess)
        {
            return;
        }

        //Retrieve the Contact from Intercom by contact email.
        Contact contact = contactsClient.List(contactEmail).contacts.FirstOrDefault();

        //If Contact exists then tag him.
        if (contact != null)
        {
            tagsClient.Tag(tagName, new List<Contact> { new Contact() { id = contact.id } });
            tagSuccess = true;
            return;
        }

        //If Contact doesn't exist then try again.
        aTimer.Enabled = true;
        elapsedTime += interval;
    }

Instead of passing to SetTimer 2 strings I want to pass it a function like TagContactByMail that takes 2 strings and doesn't return anything.

 private void SetTimer(string tagName, string contactEmail)
        {
            //Execute the function every x seconds.
            aTimer = new Timer(interval);
            //Attach a function to handle.
            aTimer.Elapsed += (sender, e) => TagContactByMail(contactEmail, tagName);
            //Start timer.
            aTimer.Enabled = true;
        }

I want SetTimer to be generic so I will be able to send it other functions as well, how can I do this?

Upvotes: 2

Views: 5375

Answers (1)

Matias Cicero
Matias Cicero

Reputation: 26281

Use Action(T1, T2):

Encapsulates a method that has two parameters and does not return a value.

private void SetTimer(Action<string, string> handle)
{
    // ...
}

You may call SetTimer like this:

SetTimer(TagContactByMail);

Edit

If what you are looking forward is passing a method prepared with the two arguments, so you just have to call it from SetTimer without knowing the actual arguments, you can do it like this:

private void SetTimer(Action handle)
{
    //Execute the function every x seconds.
    aTimer = new Timer(interval);
    
    //Attach a function to handle.
    aTimer.Elapsed += (sender, e) => handle();
    
    //Start timer.
    aTimer.Enabled = true;
}

And then, you may call SetTimer like this:

public void AddTagToContact(string tagName, string contactEmail)
{
    SetTimer(() => TagContactByMail(contactEmail, tagName));
    aTimer.Dispose();
}

Upvotes: 2

Related Questions