Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are instance methods converted to delegates?

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?

like image 844
UghSegment Avatar asked Dec 27 '22 12:12

UghSegment


2 Answers

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:

  • http://blog.slaks.net/2011/06/open-delegates-vs-closed-delegates.html
  • http://blog.slaks.net/2011/06/delegates-vs-function-pointers-part-4-c.html
like image 95
SLaks Avatar answered Jan 16 '23 04:01

SLaks


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.

like image 33
CubeSchrauber Avatar answered Jan 16 '23 05:01

CubeSchrauber