In this blog post, we will learn how we can pass a function as a parameter in C# or a method as a parameter in C#.

 

 

Pass Function As A Parameter To Another Function In C# Using Func Delegate

We can use the Func delegate as a parameter into a method.

There are several overloads to this method where it takes input and output type parameters.

Let's see how we can use the Func delegate and pass a method as a parameter to another method in C#.

 

// Main method // Execution starts here public static void Main() { ThisFunctionTakesAnotherFunction(Function1, 9); Console.ReadLine(); } // Function 1 is a normal static function public static int Function1(int number) { return number * 10; } // This Function takes a function parameter and some other parameters as well public static void ThisFunctionTakesAnotherFunction(Func function, int number) { var result = function(number); Console.WriteLine(result); }

 

Result:

 

90

 

Let's understand what's happening in the above C# code.

We have created a method called Function1 which takes in an integer parameter and it does some basic multiplication.

We want to pass this method as a parameter to another method.

We have created another method called ThisFunctionTakesAnotherFunction which takes a function as a parameter.

We make use of the Func delegate to pass in the method to another method which then returns a value.