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

  1. Use Func Delegate to Pass a Method as a Parameter in C
  2. Use Action Delegate to Pass a Method as a Parameter in C

This article will introduce different methods to pass a method as a parameter in C# function.

  • Using Func delegate
  • Using Action delegate

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

We will use the built-in delegate Func to pass a method as a parameter. A delegate acts like a function pointer. The correct syntax to use this delegate is as follows.

public delegate returnType Func<in inputType, out returnType>(InputType arg);

The built-in delegate Func has N parameters. The details of its parameters are as follows.

Parameters Description
inputType mandatory It is the type of input values for this delegate. There can be N number of input values.
returnType mandatory It is the type of the return value. The last value of this delegate is considered as the return type.

The program below shows how we can use the Func delegate to pass a method as a parameter.

public class MethodasParameter
{
    public int Method1(string input)
    {
        return 0;
    }

    public int Method2(string input)
    {
        return 1;
    }

    public bool RunMethod(Func<string, int> MethodName)
    {
        int i = MethodName("This is a string");
        return true;
    }

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

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

We can also use the built-in delegate Action to pass a method as a parameter. The correct syntax to use this delegate is as follows.

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

The built-in delegate Action can have 16 parameters as input. The details of its parameters are as follows.

Parameters Description
T mandatory It is the type of input values for this delegate. There can be 16 input values.

The program below shows how we can use the Action delegate to pass a method as a parameter.

public class MethodasParameter
{
    public int Method1(string input)
    {
        return 0;
    }

    public int Method2(string input)
    {
        return 1;
    }

    public bool RunTheMethod(Action myMethodName)
 {
      myMethodName();
      return true;
 }
  RunTheMethod(() => Method1("MyString1"));
}

Related Article - Csharp Method

  • How to Sort a List by a Property in the Object in C#
  • Related Article - Csharp Parameter

  • How to Sort a List by a Property in the Object in C#
  • comments powered by Disqus