Can somebody explain what is the exact reason behind using Action<T> and Predicate<T> as delegates in C#
Can somebody explain what is the exact reason behind using Action<T> and Predicate<T> as
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Are you asking why they exist, or why they’re defined as delegates?
As to why they exist, perhaps the best reason is convenience. If you want a delegate that returns no value and takes a single parameter of some type, they you could define it yourself:
And then later create one:
And, of course, you’d have to do that for every different type you want to have such a method.
Or, you can just use
Action<T>:Of course, you can shorten that to:
As to “why are they delegates?” Because that’s how function references are manipulated in .NET: we use delegates. Note the similarities in the examples above. That is,
MyDelegateis conceptually the same thing as anAction<int>. They’re not exactly the same thing, since they have different types, but you could easily replace every instance of thatMyDelegatein a program withAction<int>, and the program would work.