Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would I use a delegate in asp.net?

I'm always looking for a way to use all the tools I can and to stretch myself just beyond where I am at. But as much as I have read about delegates, I can never find a place to use them (like Interfaces, Generics, and a lot of stuff, but I digress.) I was hoping someone could show me when and how they used a delegate in web programming for asp.net c#(2.0 and above).

Thank you and if this wrong for Stack Overflow, please just let me know.

like image 395
johnny Avatar asked Mar 11 '09 15:03

johnny


People also ask

When should delegate be used?

Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.

What is the advantage of using delegates in C#?

Delegates allow methods to be passed as parameters. Delegates are type safe function pointer. Delegate instances attach or detach a method at run time making it more dynamic and flexible to use. Delegates can invoke more than one method using the Multicast feature.

Why We Use delegates and events in C#?

A delegate is a way of telling C# which method to call when an event is triggered. For example, if you click a Button on a form, the program would call a specific method. It is this pointer that is a delegate. Delegates are good, as you can notify several methods that an event has occurred, if you wish so.

What is difference between delegate and event?

Events Have Private InvocationEvents are typically public class members. By comparison, delegates are often passed as parameters and stored as private class members, if they are stored at all.


1 Answers

You can use delegates whenever you know you will want to take some action, but the details of that action will depend on circumstances.

Among other things, we use delegates for:

  • Sorting and filtering, especially if the user can choose between different sorting/filtering criteria
  • Simplifying code. For example, a longish process where the beginning and end are always the same, but a small middle bit varies. Instead of having a hard-to-read if block in the middle, I have one method for the whole process, and pass in a delegate (Action) for the middle bit.
  • I have a very useful ToString method in my presentation layer which converts a collection of anything into a comma-separated list. The method parameters are an IEnumerable and a Func delegate for turning each T in the collection into a string. It works equally well for stringing together Users by their FirstName or for listing Projects by their ID.
like image 196
Helen Toomik Avatar answered Sep 21 '22 13:09

Helen Toomik