It seems simple enough how static methods are invoked in delegates, as all of their parameters will be passed to them when the delegate itself is invoked.
However when an instance method is added to a delegate, the 'this' parameter is seemingly ignored during the invocation of the delegate, and so I can only imagine that it is saved alongside the delegate itself - similar to what a closure can do with other parameters.
Q: Will a closure be created by the compiler when an instance method is passed to a delegate, or is there a different mechanism by which this is accomplished?
No.
The Delegate
class has a Target
property which stores the value of this
to pass when calling the method.
In other words, a Delegate
actually stores two things: A function pointer and a value for the first parameter.
A delegate that contains a target is called a closed delegate, since it closes over the first parameter.
In fact, this is actually, how closures work. When the compiler creates a closure for a delegate, it will create a class that holds the variables that are closed over, and store that class as the delegate's Target
.
For more information, see my blog posts:
Have a look at the (underlying) Delegate class. It defines a member called Target
which defines the instance. In case of a static method Target
is associated with the class itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With