Questions to ask about delegates

5

I have not yet fully absorbed the use of delegates, at what point I really should use a delegate and why it's built. So I ask the community the following question. What is really a delegate? That is the question and it requires a single answer.

    
asked by anonymous 11.06.2015 / 14:46

2 answers

4
  

Delegate is a type of C # (and other .Net languages) that represents a particular method signature (defines the type of parameters and method return).

We can declare a delegate in the same way we declare a class (with a very different syntax, of course, but with a similar concept).

Following with the analogy, a variable of the type of a certain class will reference an object of that type, whereas a variable of the type of a certain delegate will reference a method with that signature.

  

Delegates make it easy to implement or offer an implementation option for some design patterns such as Delegation , Inversion of control > and Observer .

You can achieve the same results using interfaces instead of delegates .

Some advantages of using delegates is to need less code and eventually have a more expressive code.

For example, if an object will delegate only the execution of a single method to another object and will not have any other interaction with that other object besides firing this single method, using interface can be an exaggeration since it has the capacity of defining a complex object with multiple members, and the delegating object is only interested in a single member. In this case delegate might be more appropriate than interface .

If you have already developed desktop graphical user interface in C # ( Windows Forms ) you are very familiar with using delegates: the forms editor code generator uses delegates and events (another facilitator) to implement the observer pattern. This is how the controls notify your code when a user clicks a button, for example.

    
11.06.2015 / 15:35
1

A delegate is a reference type that can be used to encapsulate a named or anonymous method. Delegates are similar to the function pointers in C ++; however, delegates are heavily typed and secure. For delegate applications.

I recommend reading this article for a detailed explanation and with examples:

link

Here's another article:

link

    
11.06.2015 / 14:55