How to Pass a Method as a Parameter in C# Function

Minahil Noor Feb 16, 2024
  1. Use a Custom Delegate to Pass a Method as a Parameter in C#
  2. Use the Func Delegate to Pass a Method as a Parameter in C#
  3. Use the Action Delegate to Pass a Method as a Parameter in C#
  4. Conclusion
How to Pass a Method as a Parameter in C# Function

In C#, the ability to pass methods as parameters brings a level of flexibility and dynamism to your code that is crucial in various scenarios. This powerful feature is made possible through the use of delegates, which act as function pointers, allowing you to encapsulate and pass methods around as if they were variables.

In this article, we’ll explore the fundamentals of passing methods as parameters and demonstrate how this technique is achieved through delegates.

Use a Custom Delegate to Pass a Method as a Parameter in C#

A delegate in C# is a type that represents references to methods with a particular parameter list and return type. It essentially acts as a function pointer, allowing you to assign and invoke methods dynamically.

Delegates are particularly handy when you need to implement callback mechanisms or pass functions as parameters.

The general syntax for a delegate declaration is as follows:

delegate ReturnType DelegateName(ParameterType1 param1, ParameterType2 param2, ...);

Here’s a breakdown of the components:

  • delegate: This keyword is used to declare a delegate.
  • ReturnType: This represents the return type of the methods that the delegate can encapsulate.
  • DelegateName: This is the name given to the delegate type.
  • (ParameterType1 param1, ParameterType2 param2, ...): This part defines the parameter list that the methods which the delegate can point to should accept.

To use this delegate in a method as a parameter, you include it in the method signature like this:

void MethodWithDelegateParameter(DelegateName methodName) {
  // Method implementation
}

Now, let’s delve into a practical example to demonstrate how to pass a method as a parameter using delegates.

using System;

class Program {
  delegate void DisplayMessage(string message);

  static void Main() {
    DisplayMessage showMessageDelegate = DisplayMessageMethod;
    MethodWithDelegateParameter(showMessageDelegate, "Hello, Delegates!");
  }

  static void MethodWithDelegateParameter(DisplayMessage displayMethod, string message) {
    displayMethod(message);
  }

  static void DisplayMessageMethod(string message) {
    Console.WriteLine(message);
  }
}

Output:

Hello, Delegates!

In this example, we first declare a delegate named DisplayMessage that represents a method taking a string parameter and returning void. Next, we define the Main method, where we instantiate the delegate with reference to the DisplayMessageMethod.

The MethodWithDelegateParameter function takes a DisplayMessage delegate and a string as parameters. Inside this method, we invoke the delegate with the provided string parameter.

Finally, we define the DisplayMessageMethod that simply writes the received message to the console.

Use the Func Delegate to Pass a Method as a Parameter in C#

Func is one of the predefined delegate types in C# that can encapsulate methods with up to 16 parameters and a return type. It is part of the System namespace and is commonly used in scenarios where a method needs to be passed as a parameter, particularly when you want to specify both input and output types.

The Func delegate is generic and is defined with the following syntax:

public delegate TResult Func<in T, out TResult>(T arg);

Here, T represents the input parameter type, and TResult represents the return type of the method. The Func delegate can handle methods with up to 16 input parameters.

Let’s consider a practical example to demonstrate how to use the Func delegate to pass a method as a parameter.

using System;

public class MethodAsParameterExample {
  public static int MultiplyByTwo(int x) {
    return x * 2;
  }

  public static void ProcessNumber(Func<int, int> operation, int number) {
    int result = operation(number);
    Console.WriteLine($"Result: {result}");
  }

  public static void Main() {
    ProcessNumber(MultiplyByTwo, 5);
  }
}

Output:

Result: 10

In this example, we have a simple method, MultiplyByTwo, that takes an integer and returns its double. The ProcessNumber function takes a Func<int, int> delegate as a parameter, representing a method that takes an integer and returns an integer.

In the Main method, we pass the MultiplyByTwo method as an argument to ProcessNumber. The Func delegate allows us to treat the MultiplyByTwo method as a parameter, and the ProcessNumber function invokes this method with the number 5.

The result is then printed to the console.

This approach enhances code reusability and promotes a more modular design, allowing the interchangeable use of different methods with the same signature. Using the Func delegate in this manner provides a clean and concise way to pass methods as parameters, contributing to the overall flexibility and maintainability of C# code.

Use the Action Delegate to Pass a Method as a Parameter in C#

The Action delegate, like the Func delegate, is a built-in delegate in C#. It represents a method that takes parameters but does not return a value (void methods). It allows you to pass methods as parameters, making it particularly useful when you want to abstract and customize behavior at runtime.

Its syntax is defined as follows:

public delegate void Action<in T>(T obj);

Here, T represents the type of the input parameter. The in keyword indicates that T is an input parameter for the delegate.

The Action delegate can also accommodate up to 16 input parameters.

Let’s delve into a practical example to showcase how the Action delegate can be employed to pass a method as a parameter.

using System;

public class MethodAsParameterExample {
  public static void PrintMessage(string message) {
    Console.WriteLine($"Message: {message}");
  }

  public static void ExecuteWithAction(Action<string> operation, string message) {
    operation(message);
  }

  public static void Main() {
    ExecuteWithAction(PrintMessage, "Hello, World!");
  }
}

Output:

Message: Hello, World!

In this example, we have a method named PrintMessage that takes a string parameter message and prints it to the console. The ExecuteWithAction method accepts an Action<string> delegate named operation and a string parameter message.

Inside ExecuteWithAction, the operation delegate is invoked with the provided message.

In the Main method, we demonstrate how to use the ExecuteWithAction method by passing the PrintMessage method as a parameter. The output will be Message: Hello, World!, indicating that the PrintMessage method was successfully invoked through the Action delegate.

This approach allows for dynamic behavior, enabling the ExecuteWithAction method to work with different operations specified by the Action delegate. It highlights the flexibility of passing methods as parameters in C# using the Action delegate, particularly when dealing with methods that don’t return a value.

Conclusion

Passing methods as parameters in C# using delegates empowers you to write more modular and flexible code. Whether you’re creating callback mechanisms, implementing event handling, or designing generic functionality, understanding how to leverage delegates to pass methods dynamically is a fundamental skill in C# development.

Related Article - Csharp Method

Related Article - Csharp Parameter