Delegates, Action and Func in C#

In this article, we will discuss the usage of Delegates, Action, and Func in C#, and when to use each of them. Their explanations will help us decide what should be included in our code, and their useful coding examples will make our process easier. At the end of this article, you will understand the whole concept of these keywords. A delegate is a type-safe function pointer that can reference a method that has the same signature as that of the delegate. The "delegate" keyword is used to declare delegates, which are used to provide callback functions and carry out event handling. A delegate that you declare can show up by itself or even nested inside another class. Action is a delegate that points to a method that in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void. A delegate type called Action is listed in the System namespace. In other words, a method having a void return type can be used with an Action delegate.

Func is a built-in generic delegate type in C#, so you typically don't need to define custom delegates explicitly. A generic delegate found in the System namespace is called Func. It has one out parameter and zero to more input parameters. The System namespace contains the definition of the Func delegate, which has one input parameter and one output parameter.


Code example of Delegate:

Given below is an example of delegate implementation.


Example:



namespace DelegatesFuncAction

{

    internal class Program

    {

      public delegate int Square(int num);

     

        static void Main(string[] args)

        {

          Square sq = delegate (int num)

          {

              return num * num;

          };

          Console.WriteLine("The result is : " +sq(5).ToString());

            Console.ReadLine();

        }

    }

}




Output:


The result is : 25




Types of Delegates in C#:


Three built-in generic delegates are available in C#, and they are as follows:

  • Predicate

  • Action

  • Func


Let’s look at each of them in detail.


Predicate Delegates in C#:


A delegate is a type that refers to a method whose signature matches the delegate's own. To transmit methods as inputs to other methods, delegates are therefore utilized. Delegates are useful for implementing callback functions and event handlers in C#. A delegate with the ability to point to one or more identically signed methods is known as a multicast delegate.  As compared to function pointers in C or C++, delegates in C# are comparable, but delegates are type-safe. Delegates are thus type-safe references that point to one or more methods with the same signatures as the delegate. A delegate is a type-safe function pointer that can refer to a method whose signature matches the delegate's own. With the "delegate" keyword, delegates are declared, and they are used to specify callback functions and implement event handling. Declaring a delegate allows you to have it appear either alone or inside another class.


The Predicate delegate's syntax is shown in the following example.



 Predicate<T>




Given below is an example of Predicate delegates implementation.

Example:



using System;

namespace DelegatesFuncAction

{

    internal class Program

    {

        static void Main(string[] args)

        {

            Predicate<string> CheckIfRobot = IsRobot;

            bool result = CheckIfRobot("Robot 8.6");

            if (result)

                Console.WriteLine("It's an Robot");

            static bool IsRobot(string modelName)

            {

                if (modelName == "Robot 8.6")

                    return true;

                else

                    return false;

            }

            Console.ReadLine();

        }

    }




Output:


 It
's an Robot





Predicate delegate with Lambda Expression:


Lambda expressions make writing delegate codes far more straightforward, simple, and readable. An illustration of a Predicate delegate with lambda expression implementation is provided below.

Example:


namespace DelegatesFuncAction

{

    internal class Program

    {

        static void Main(string[] args)

        {

          Predicate<string> CheckIsRobot = modelName => {

                if (modelName == "Robot 8.6") return true;

                else return false;

            };

           

            bool result = CheckIsRobot("Robot 8.6");

            if (result) Console.WriteLine("It's an Robot");

            Console.ReadLine();

        }

    }

}




It is how pre-made delegates can be used directly without being declared.


Output:


 It's an Robot





Action Generic Delegate in C#:


In C#, the System namespace also contains the Action Generic Delegate. It requires one or more input parameters but produces no output. This delegate can accept up to 16 input parameters of various or similar data types. In other words, an Action delegate can be used with a method that has a void return type. Simply we can say Action is a delegate that points to a method that in turn accepts one or more arguments but returns no value.


To create an action delegate in C#, use the following syntax:

 

 Action<TParameter>



An action delegate doesn't return a value, an Action delegate can be used with a method that has a void return type. Action delegates can have 0 to 16 input parameters.


Given below is an example of Action Implementation.

Example:


using System;

namespace DelegatesFuncAction

{

    internal class Program

    {

        private static int result;

       

        static void Main(string[] args)

        {

            Action<int, int> Addition = AddNumbers;

            Addition(10, 20);

            Console.WriteLine($" The Result is : {result}");

            Console.ReadLine();

        }

        private static void AddNumbers(int param1, int param2)

        {

            result = param1 + param2;

        }

    }

}




Output:


 The
Result is : 30



Action with Lambda Expression:


Writing delegate codes is considerably simpler, easier, and more readable thanks to lambda expression. Given below is an example of Action with lambda expression implementation.


Example:


using System;

namespace DelegatesFuncAction

{

    internal class Program

    {

        private static int result;

        static void Main(string[] args)

        {

          Action<int, int> Addition = (param1, param2) => result = param1 + param2;

          Addition(70, 20);

          Console.WriteLine($"The result is :  {result}");

           

            Console.ReadLine();

        }

    }

}




Output:


 The result is :  90




Note: Use the Action Generic delegate in C# whenever your delegate doesn't return any value, regardless of whether it accepts any input parameters or not.



Func Generic Delegate in C#:


The Func Generic Delegate in C# is present in the System namespace. A single-out parameter is returned by this delegate after accepting one or more input arguments. The final input is taken into account as the return value. Up to 16 input parameters of various or the same data types can be passed to the Func Generic Delegate in C#. There can be only one return type. The input parameter is not required, but the return type is required. Func is a delegate that points to a method that accepts one or more arguments and returns a value.


A Func delegate in C# is declared using the following syntax:


 Func<TParameter, TOutput>




The System namespace defines the Func delegate, which has one input parameter and one output parameter, as illustrated below.

Syntax:


namespace System

{    

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

}




The following Func delegate takes two input parameters and one return type:

Syntax:


 public delegate TResult Func<in T1, in T2, out TResult>(T1 arg, T2 arg2)

 


The final parameter enclosed in angle brackets < > is taken into account as the return type, whereas the other parameters are taken into account as input parameter types.


Given below is an example of Func implementation in a program.

Func with 0 parameters.

 

 Func<int> SomeMethodName;




Example:


using System;

namespace DelegatesFuncAction

{

    internal class Program

    {

        static int Sum(int x, int y)

        {

            return x + y;

        }

        static void Main(string[] args)

        {

            Func<int, int, int> add = Sum;

            int result = add(10, 10);

            Console.WriteLine("The result is: " +result);

            Console.ReadLine();

        }

    }

}




Output:


 The result is: 20



A Func delegate type may have 0 to 16 different sorts of input arguments. It must however have an out parameter for the outcome. For instance, the Func delegate that follows has only an out argument and no input parameters.



Func with Lambda Expression:


Lambda Expression makes the writing of delegate codes much easier, simpler, and more readable. Given below is an example of Func with lambda expression implementation.



using System;

namespace DelegatesFuncAction

{

    internal class Program

    {

        static void Main(string[] args)

        {

           

           Func<int, int, int> Addition = (param1, param2) => param1 + param2;

           int result = Addition(30, 20);

           Console.WriteLine($"The Result is : {result}");

            Console.ReadLine();

        }

    }

}



Output:


 The
Result is : 50 



Note: Use the Func Generic delegate in C# whenever your delegate returns some value, whether it accepts any input parameters or not.


Conclusion:


In this post, we have gone through the generic delegates like a predicate, action, and Func and our aim is to use the examples in the post. We should be able to comprehend how generic delegates are used after reading this article. We have implemented here all the generic delegates with practical coding examples.

I sincerely hope you had fun and learned something from reading this article. Comment below with your ideas and suggestions.


Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee