Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Action<T> and Predicate<T> used or defined as delegates?

Tags:

c#

delegates

Can somebody explain what is the exact reason behind using Action<T> and Predicate<T> as delegates in C#

like image 511
Wondering Avatar asked Nov 30 '22 17:11

Wondering


1 Answers

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.

like image 197
Jim Mischel Avatar answered Dec 14 '22 22:12

Jim Mischel