C# Actions and Func’s

Print Friendly, PDF & Email

C# Actions and Func’s

Within C# we can create a generic method that collects data and pass into that method either and ‘Action’ or a ‘Func’ to process that data. A good example of this might be a method that walks a product structure. we can pass into that method different ways to process that data.

Processor

The processor below contains three generic methods, the first two take in Actions without a parameter and the second with. The third method takes in a Func.

    public class Processor
    {
        public void loopcounter(Action functionToProcess)
        {
            for (int i = 0; i < 5; i++)
            {
                functionToProcess();
            }
        }

        public void loopcounter2(Action<int> functionToProcess)
        {
            for(int i = 0; i < 5; i++)
            {
                functionToProcess(i);
            }
        }

        public void loopcounter3(Func<int, int> functionToProcess)
        {
            int k = functionToProcess(10);
            Console.WriteLine("k = {0}", k);
        }
    }

Program1

Program 1 has three methods, the first two are void these can be used with the ‘Action’ and the third with a ‘Func’.

public class Program1
    {
        public void ActionToPass(int x)
        {
            Console.WriteLine("x = {0}", x);
        }

        public void ActionToPass()
        {
            Console.WriteLine("a = {0}","a");
        }

        public int FunctionToPass(int x)
        {
            return x + 45;
        }
    }

Program2

Program 2 also contains three methods, the first two are void these can be used with the ‘Action’ and the third with a ‘Func’, but their behaviors could be different.

public  class Program2
    {
        public void ActionToPass(int y)
        {
            Console.WriteLine("y = {0}", y);
        }

        public void ActionToPass()
        {
            Console.WriteLine("b = {0}","b");
        }

        public int FunctionToPass(int x)
        {
            return x - 45;
        }
    }

Main Program

The main program can then execute the Processor methods passing in the unique program methods to handle the data differantly.

Processor processor = new Processor();
Program1 program1 = new Program1();
Program2 program2 = new Program2();

processor.loopcounter(program1.ActionToPass);
processor.loopcounter(program2.ActionToPass);

processor.loopcounter2(program1.ActionToPass);
processor.loopcounter2(program2.ActionToPass);

processor.loopcounter3(program1.FunctionToPass);
processor.loopcounter3(program2.FunctionToPass);

Output

In the output we can see how the data is handled differently due to the Actions and Func’s.

a = a
a = a
a = a
a = a
a = a
b = b
b = b
b = b
b = b
b = b
x = 0
x = 1
x = 2
x = 3
x = 4
y = 0
y = 1
y = 2
y = 3
y = 4
k = 55
k = -35