Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you use delegates in C#? [closed]

Tags:

c#

.net

delegates

What are your usage of delegates in C#?

like image 832
Maxime Rouiller Avatar asked Oct 10 '08 13:10

Maxime Rouiller


People also ask

What is delegates why to use delegates?

1. A delegate is a type safe function pointer. That is, they hold reference(Pointer) to a function. The signature of the delegate must match the signature of the function, the delegate points to, otherwise you get a compiler error. This is the reason delegates are called as type safe function pointers.

What is the benefit of delegates in C#?

Advantages to using them in design:Allow you to develop libraries and classes that are easily extensible, since it provides an easy way to hook in other functionality (for example, a where clause in LINQ can use a delegate [Func<T,bool>] to filter on, without having to write new code in the Where method.

Where do you put delegates?

If you have an common use for your delegates, you should store them on a common place, but if you only use it in your class then put it in the same class. Show activity on this post. You don't have a Classes, Structs, and Enums folder.


1 Answers

Now that we have lambda expressions and anonymous methods in C#, I use delegates much more. In C# 1, where you always had to have a separate method to implement the logic, using a delegate often didn't make sense. These days I use delegates for:

  • Event handlers (for GUI and more)
  • Starting threads
  • Callbacks (e.g. for async APIs)
  • LINQ and similar (List.Find etc)
  • Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)
like image 173
Jon Skeet Avatar answered Oct 13 '22 19:10

Jon Skeet