Can somebody explain what is the exact reason behind using Action<T>
and Predicate<T>
as delegates in C#
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:
public delegate void MyDelegate(int size);
And then later create one:
MyDelegate proc = new MyDelegate((s) => { // do stuff here });
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>
:
Action<int> proc = new Action<int>((s) => { /* do stuff here */ });
Of course, you can shorten that to:
Action<int> proc = (s) => { /* do stuff here */ });
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, MyDelegate
is conceptually the same thing as an Action<int>
. They're not exactly the same thing, since they have different types, but you could easily replace every instance of that MyDelegate
in a program with Action<int>
, and the program would work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With