pass function as parameter c# code example

Example 1: pass function in as variable C#

void Function(Func<int> function) //Func<Type> function is the way to define a function
{
  function(); //Fun the function
}
void DoStuff()
{
  Function(function); //Run the function with another function as the input variable
}
int function() //The function to be passed in
{
  Console.WriteLine("Returns 0");
  return 0;
} 
//Func<Type> type cannot be void. The function must return something

Example 2: Pass Method as Parameter using C#

public class Class1
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
}