Action, Func, and Predicate

action func and predicate

Action Func and Predicate are built-in delegates in C#. They are useful when you want to pass some logic as a parameter to another method. To get more clarity on delegates, please refer to this post. All of them pass logic to the called method, there is a subtle difference between them.

Action:

When you want to use a delegate that may or may not take arguments and does not return any value, you used Action. Here is an example

public class First
{
    public void Called(Action doWork)
        {
                doWork();
        }
}

class Second
{
        public void Caller()
        {
                First obj = new First();
                obj.Called(() => { Console.WriteLine("Work done"); });
        }
}
//Output
Work done

You can even pass parameters to it, To pass the parameter you need to use the generic version of Action, i.e. Action<type1, type1, type1,…> I have highlighted that in Delegates in C# post.

Func:

When you want to use a delegate that may or may not take arguments and returns any value, you used Action. Here is an example, DoWork will return a message after some work is done.

 public class First
 {
         public void Called(Func<string> DoWork)
         {
                 Console.WriteLine(DoWork());
         }
 }

 class Second
 {
         public void Caller()
         {
                 First obj = new First();
                 obj.Called(() => { return "Work done at " + DateTime.Now; });
         }
 }
 
 //Output
Doing work...
Work done at 22-01-2022 08:42:12 PM

It will always have one generic parameter, i.e. return type, and can have multiple input parameters.

Func<inputType1, inputType2, inputType3, returnType>

Please note that the last parameter will be considered as the return type.

Predicate:

The predicate is a special type of Func. It will always return a Boolean so there is no need to explicitly pass return type. This always requires one input parameter. It is the oldest generic delegate, if Action and Func were there before, this delegate might not have been there because Func would have been enough. An example of Predicate is as below

public class First
{
        public void Called(Predicate<int> IsBiggerThan2)
        {
                Console.WriteLine(IsBiggerThan2(5));
        }
}

class Second
{
        public void Caller()
        {
                First obj = new First();
        obj.Called((arg1) => {
            return arg1 > 2;
                });
        }
}
Output: True

Summary

Action Func and Predicate are three special delegated built into C#.
Action performs a task and does not return any value. Func performs a task and returns a value. The predicate is a special type of Func that always returns a boolean value.

CategoriesC#

Leave a Reply

Your email address will not be published.

Coding Crest Back To The Top