Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some common scenarios where delegates should be used? [duplicate]

Tags:

c#

.net

delegates

I understand how delegates and events work. I can also imagine some common scenarios where we should implement events, but I’m having harder times understanding in what situations should delegates be used.

thanx

REPLYING TO USER KVB'S POST:

a)

You can basically use delegates wherever you would otherwise use a one-method interface.

I think I somewhat understand the following:

  • Class C could define method C.M, which would take as an argument an interface IM. This interface would define a method IM.A and thus anyone wanting to call C.M would need to implement this interface.

  • Alternatively, method C.M could take ( instead of an interface IM ) as an argument a delegate D with the same signature as method IM.A.

But what I don’t understand is why can’t C.M also use as its parameter a delegate D even if our interface IM defines several other methods besides method A? Thus, the other methods of class C could require as their argument an interface IM, but C.M could instead require a delegate D ( assuming C.M only needs to call method A and not any of the other methods defined within IM ) ?

b)

var list = new List<int>(new[] { 1, 2, 3 });
var item = list.Find(i => i % 2 == 0);
  • Is the above code an example of what user jpbochi calls ( see hers/his post in this thread ) dependency injection?

  • I assume the above code couldn’t be implemented using events instead of “pure” delegates?

like image 492
AspOnMyNet Avatar asked Feb 15 '10 18:02

AspOnMyNet


2 Answers

When you want to provide a function, that will be executed on some event. You give to the event's Event handler a delegate of a function that is about to be executed. They are great when you do event driven programming.

Also when you have functions that have functions as arguments (LINQ expressions, predicates, map-functions, aggregate functions, etc). This functions are generally called higher level functions.

In addition you can wrap some functionality, when the caller has no need access other properties, methods, or interfaces on the object implementing the method. In this case it replaces inheritance, somehow.

like image 83
anthares Avatar answered Oct 05 '22 02:10

anthares


In my point of view, delegates are the simplest means of dependency injection. When a component receives a delegate (either in an event or in a regular method) it is allowing another component to inject behavior to it.

like image 30
jpbochi Avatar answered Oct 05 '22 01:10

jpbochi