Delegate Basics Part 2 – Method & Target

In the previous post, I wrote that a delegate is a class containing a reference to a method. I’ve created a simple example and with the help of the JetBrains decompiler, I’ll show you the class created under-the-hood by the compiler.

In this example, I have the delegate “SquarerDel which takes an integer value and returns an integer.

In the Calculator class, I have the method “Square” which takes an integer value and returns the square of that value e.g. 5 returns 25 etc

I create an instance of the Calculator class and then assign it’s “Square” method to my delegate “del”.

Lastly, I call the delegate with 5 via Invoke ( see all this below )

Delegate4.JPG

Delegate2

Delegate3

What does the compiler do when you use a delegate ?
Generates a class for the delegate
Constructor takes an object and integer value
The integer represents a memory address to the method – execution starts at that address
The object is the class to invoke the method on. The delegate also contains 3 functions – BeginInvoke, EndInvoke, Invoke. More on these later.

See the IL below for the class definition for the delegate.

DelegateIL

Design a site like this with WordPress.com
Get started