Basic Structure of Delegate in C#

Tayfun Güven
2 min readJul 2, 2020

Hi everyone!

In this story, I will cover the C# delegates, which are similar to pointers in C and C++, with its basic structure.

Figure 1 — Simple Diagram of the Delegate

A delegate is a reference type, so they can be able to hold the addresses of methods and themselves. Also, a delegate can point all of the methods inside the class.

There are four usage of delegate for methods:

  • Delegate with no return type and no parameters,
  • Delegate with no return type but with parameters,
  • Delegate with a return type but with no parameters,
  • Delegate with a return type and parameters

When we wanted to call a method inside of another method or main method, we will briefly call the method directly inside them as shown below:

However, if we want to call a method by using delegate, since delegates are reference type, firstly we need to define the reference, then we create a new object with a delegate. So, we can invoke the methods with a delegate.

As a benefit of delegates, If there are more than one methods exist such as addition, division, multiplication, etc. and you want to use them inside the main method or another method, or you want to use the same values inside different methods; you can simply use “+=” operator with delegate object in order for adding a new method or you can briefly use “-=” operator for removing methods. In this part, when we conclude the general function of the delegate, we can say that you can point more than one method by using delegate, but only the last one on the top of the stack can be compiled if there exists so it does not mean that all pointed methods have to be compiled. Here is a good example of using plural methods:

In conclusion, delegate can be able to act like a pointer and it’s a reference type, therefore it provides passing of the all pointed methods as a parameter. Furthermore, as in the example I gave above, you can add and remove methods dynamically, so it makes delegates more flexible. And with the Multicast delegate, you can invoke more methods.

As a final words, you can add whole invoked methods inside an array with “GetInvocationLıst();” method and loop them with foreach in order to see compiled methods. And with the “DynamicInvoke();”, we can compile the referenced methods inside the loop.

--

--