Doubts about the use of delegates

Asked

Viewed 490 times

5

I still have not been able to fully absorb the use of the delegates, at what point I really should use a delegate and why of their construction. Then I ask the following question to the community. What is a delegate really? That is the question and it requires a single answer.

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 the return of the method).

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

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

Delegates facilitate implementation or offer an option to implement some Patterns design as Delegation, Inversion of control and Observer.

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

Some advantages to use delegates is to need less code and possibly have a more expressive code.

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

If you have ever developed desktop graphical user interface in C# (Windows Forms) you are quite familiar with the use of delegates: the code generator of the Forms editor uses delegates and Events (another facilitator) to implement Pattern Observer. This is how controls notify your code when a user clicks on a button, for example.

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.