Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing a function as an argument in C#

I’m trying to pass a function as an argument just like this:

void AvoidSpawn(float sRate, function f) 
    {
        float calculateRate = 0;
        if(Time.time>=calculateRate)
        {
            f();
            calculateRate = Time.time + spawnRate;
        }
    }

I don’t know how to use a function as an argument and pass it and I would like to replace function f with something that works.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For a function that doesn’t return any value (a void method), there are various Action delegates.

For a function that does return a value, you need Func and friends.

There are various versions to account for a number of parameters (up to 16, nowadays).

So you can define your function as

void AvoidSpawn(float sRate, Action f) 
{
   // ...
   f();
   // ...
}

And either call it with a lambda:

AvoidSpawn(1.0f, () => Console.WriteLine("Avoiding spawn"));

or mention another method

AvoidSpawn(1.0f, SomeVoidMethod);

Note: do not use () there, you don’t want to call that method yet.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading