Generic Delegates in C#

Generic Delegates in C# with Real-Time Examples

In this article, I am going to discuss the Generic Delegates in C# with real-time examples. Please read the Delegates in C# article before proceeding to this article. As part of this article, we are going to discuss the following pointers in detail.

  1. What are Generic Delegates in C#?
  2. Types of Generic Delegates in C#.
  3. Why do we need the Generic Delegates?
  4. Func Generic Delegate in C#?
  5. Action Generic Delegate in C#?
  6. Predicate Generic Delegate in C#?
  7. Examples to understand Generic Delegates in C#.
What are Generic Delegates in C#?

The Generic Delegates in C# was introduced as part of .NET Framework 3.5 which don’t require defining the delegate instance in order to invoke the methods. To understand the Generic Delegates in C# you should have the basic knowledge of Delegates.

Types of Generic Delegates in C#

C# provides three built-in generic delegates, they are

  1. Func
  2. Action
  3. Predicate
Why do we need the Generic Delegates?

Let us understand the need for Generic Delegates with an example. In order to understand this, let us first understand how we use delegates to invoke methods.

Example:

Let us say we have the following three methods and we want to invoke these methods using delegates.

Why do we need the Generic Delegates?

As you can see the AddNumber1 method takes three parameters and returns a value of double type. Similarly, the AddNumber2 method takes three parameters but it does not return any value. The third method i.e. the CheckLength method takes one string parameter and return a Boolean value.

If we want to invoke the above three methods using delegates then we need to create three delegates whose signature should match with the above three methods as shown in the below image.

Delegates in C#

As you can see in the above image, we create three delegates. Let’s invoke the methods using the respective delegate instance as shown in the below image.

Without C# Generic Delegates

Following is the complete example code.
namespace GenericDelegateDemo
{
    public class GenericDelegates
    {
        public delegate double AddNumber1Delegate(int no1, float no2, double no3);
        public delegate void AddNumber2Delegate(int no1, float no2, double no3);
        public delegate bool CheckLengthDelegate(string name);

        static void Main(string[] args)
        {

            AddNumber1Delegate obj1 = new AddNumber1Delegate(AddNumber1);
            double Result = obj1.Invoke(100, 125.45f, 456.789);
            Console.WriteLine(Result);

            AddNumber2Delegate obj2 = new AddNumber2Delegate(AddNumber2);
            obj2.Invoke(50, 255.45f, 123.456);

            CheckLengthDelegate obj3 = new CheckLengthDelegate(CheckLength);
            bool Status = obj3.Invoke("Pranaya");
            Console.WriteLine(Status);

            Console.ReadKey();
        }

        public static double AddNumber1(int no1, float no2, double no3)
        {
            return no1+ no2 + no3;
        }

        public static void AddNumber2(int no1, float no2, double no3)
        {
            Console.WriteLine( no1 + no2 + no3);
        }

        public static bool CheckLength(string name)
        {
            if (name.Length > 5)
                return true;
            return false;
        }
    }
}
OUTPUT:

Generic Delegates in C#

As of now, this is the way, we use delegates to invoke methods. The question that comes to our mind is

Do we really need to create the Delegates?

The answer is no. C# provides some generic delegates which can do the job for us. C# provides three Generic Delegates, they are as follows

  1. Func
  2. Action
  3. Predicate
What is Func Generic Delegate in C#?

The Func Generic Delegate in C# is present in the System namespace. This delegate takes one or more input parameters and returns one out parameter. The last parameter is considered as the return value.

The Func Generic Delegate in C# can take up to 16 input parameters of different types. It must have one return type. The return type is mandatory but the input parameter is not.

Note: Whenever your delegate returns some value, whether by taking any input parameter or not, you need to use the Func Generic delegate in C#.

What is Action Generic Delegate in C#?

The Action Generic Delegate in C# is also present in the System namespace. It takes one or more input parameters and returns nothing. This delegate can take a maximum of 16 input parameters of the different or same type

Note: Whenever your delegate does not return any value, whether by taking any input parameter or not, then you need to use the Action  Generic delegate in C#.

What is Predicate Generic Delegate in C#?

The Predicate Generic Delegate in C# is also present in the System namespace. This delegate is used to verify certain criteria of the method and returns output as Boolean, either True or False.

It takes one input parameter and always returns a Boolean value which is mandatory. This delegate can take a maximum of 1 input parameter and always return the value of the Boolean type.

Note: Whenever your delegate returns a Boolean value, by taking one input parameter, then you need to use the Predicate Generic delegate in C#.

Examples to understand Generic Delegates in C#.

Let’s understand the above three generic delegates in C# with an example. In our first example, we created three methods,

  1. The addnumber1 method takes three parameters and returns a double value. Here we will use the Func Generic Delegate to achieve the same thing as we achieve in the first example.
  2. Similarly, the addnumber2 method takes three parameters but does not return any value. Here we will use the Action Generic Delegate to achieve the same thing as we achieve in the first example.
  3. The checklength method takes one string parameter and returns a boolean value. Here we will use the Predicate Generic Delegate to achieve the same thing as we achieve in the first example.

First, remove the three Delegates that we created.

The following image shows how to use the Func Generic Delegate in C#.

Func Generic Delegates in C#

As shown in the above image, the Func Generic Delegate takes four parameters, the first three are input parameters and the last one is the return value. To the Func Generic Delegate constructor, we pass the AddNumber1 method which is going to execute when we invoke the Func delegate.

Let’s see how to use the Action Generic Delegate in C#. Have a look at the below image.

Action Generic Delegates in C#

As shown in the above image, the Action Generic Delegate takes three input parameters. To the Action Generic Delegate constructor, we pass the AddNumber2 method which is going to execute when we invoke the Action delegate.

Let’s see how to use the Predicate Generic Delegate in C#. Have a look at the below image.

Predicate Generic Delegate in C#

As shown in the above image, the Predicate Generic Delegate takes one string input parameters. To the Predicate Generic Delegate constructor, we pass the CheckLength method which is going to execute when we invoke the Predicate Generic delegate. This delegate can take a maximum of 1 input parameter and 0 return values. By default, it returns a Boolean value.

Below is the complete code.
namespace GenericDelegateDemo
{
    public class GenericDelegates
    {
        static void Main(string[] args)
        {
            Func<int, float, double, double> obj1 = new Func<int, float, double, double>(AddNumber1);
            double Result = obj1.Invoke(100, 125.45f, 456.789);
            Console.WriteLine(Result);
            
            Action<int, float, double> obj2 = new Action<int, float, double>(AddNumber2);
            obj2.Invoke(50, 255.45f, 123.456);
            
            Predicate<string> obj3 = new Predicate<string>(CheckLength);
            bool Status = obj3.Invoke("Pranaya");
            Console.WriteLine(Status);

            Console.ReadKey();
        }

        public static double AddNumber1(int no1, float no2, double no3)
        {
            return no1+ no2 + no3;
        }

        public static void AddNumber2(int no1, float no2, double no3)
        {
            Console.WriteLine( no1 + no2 + no3);
        }

        public static bool CheckLength(string name)
        {
            if (name.Length > 5)
                return true;
            return false;
        }
    }
}
OUTPUT:

Generic Delegates in C#

Let’s see how to use Lambda Expression along with Generic Delegates in C#.
namespace GenericDelegateDemo
{
    public class GenericDelegates
    {
        static void Main(string[] args)
        {
            Func<int, float, double, double> obj1 = (x, y, z) =>
            {
                return x + y + z;
            };

            double Result = obj1.Invoke(100, 125.45f, 456.789);
            Console.WriteLine(Result);
            
            Action<int, float, double> obj2 = (x, y, z) =>
            {
                Console.WriteLine(x + y + z);
            };
            obj2.Invoke(50, 255.45f, 123.456);
            
            Predicate<string> obj3 = new Predicate<string>(CheckLength);
            bool Status = obj3.Invoke("Pranaya");
            Console.WriteLine(Status);

            Console.ReadKey();
        }
        public static bool CheckLength(string name)
        {
            if (name.Length > 5)
                return true;
            return false;
        }
    }
}
OUTPUT:

Generic Delegates OUTPUT in C#

Points to remember while working with C# Generic Delegates:
  1. Func, Action, and Predicate are generic inbuilt delegates which are present in System namespace which is introduced in C# 3.
  2. All these three delegates can be used with the method, anonymous method and lambda expressions.
  3. The Func delegates can contain a maximum of 16 input parameters and must have one return type.
  4.  Action delegate can contain a maximum of 16 input parameters and does not have any return type.
  5. The Predicate delegate should satisfy some criteria of a method and must have one input parameter and one Boolean return type either true or false which is by default. Means we should not have to pass that to the Predicate

In the next article, I am going to discuss the Anonymous method real-time example in C#. Here, in this article, I try to explain Generic Delegates in C# with some examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

2 thoughts on “Generic Delegates in C#”

  1. wats beauty or benefits of invoking method via delegate over trigger method directly in the context of callback?

Leave a Reply

Your email address will not be published. Required fields are marked *