Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as a function parameter

Tags:

c#

unity3d

Unity C# doesn't seem to recognize the Func<> symbol as a function delegate. So, how can I pass a function as a function parameter?

I have an idea that Invoke(functionName, 0) might help. But I am not sure whether it actually invokes the function instantly, or waits for the end of the frame. Is there another way?

like image 322
Coatl Avatar asked Feb 19 '19 18:02

Coatl


People also ask

Can you use a function as a parameter of another function?

Functions, like any other object, can be passed as an argument to another function.

How do you pass a function as a parameter in C++?

C++ has two ways to pass a function as a parameter. As you see, you can use either operation() or operation2() to give the same result.

Can you pass a function as a parameter to another function in Python?

Summary. In Python you can pass function objects in to other functions. Functions can be passed around in Python. In fact there are functions built into Python that expect functions to be given as one or more of their arguments so that they can then call them later.

Can you pass a function as a parameter of another function in JavaScript?

Passing a function as an argument to the function is quite similar to the passing variable as an argument to the function. so variables can be returned from a function. The below examples describe passing a function as a parameter to another function.


1 Answers

You can use Action to do that

using System;

// ...

public void DoSomething(Action callback)
{
    // do something

    callback?.Invoke();
}

and either pass in a method call like

private void DoSomethingWhenDone()
{
    // do something
}

// ...

DoSomething(DoSomethingWhenDone);

or using a lambda

DoSomething(() =>
    {
        // do seomthing when done
    }
);

you can also add parameters e.g.

public void DoSomething(Action<int, string> callback)
{
    // dosomething

    callback?.Invoke(1, "example");
}

and again pass in a method like

private void OnDone(int intValue, string stringValue)
{
    // do something with intVaue and stringValue
}

// ...    

DoSomething(OnDone);

or a lambda

DoSomething((intValue, stringValue) =>
    {
        // do something with intVaue and stringValue
    }
);

Alternatively also see Delegates

and especially for delegates with dynamic parameter count and types check out this post

like image 163
derHugo Avatar answered Sep 21 '22 20:09

derHugo