I'm currently working through the documentation of the Delegate class in C# and am running into some terminology that is tripping me up. I have a conceptual understanding of what a delegate is coming from C function pointers and C++ lambdas etc, its the fine details in C# I'm trying to pick up
The specific lines/terms from the documentation and the questions regarding them are listed below:
A delegate is an instance of a delegate type that has references to:
- An instance method of a type and a target object assignable to that type. (emphasis mine)
I understand the instance method part. For example:
FooDelegateType foo = FooInstanceMethod;
What however is meant by "and a target object assignable to that type"? In the example above, does target object refer to a specific instance of the type containing the definition for FooInstanceMethod?
Next:
- An instance method of a type, with the hidden this parameter exposed in the formal parameter list (emphasis mine). The delegate is said to be an open instance delegate.
I'm having a hard time visualizing what this means. Does it mean the instance method has an explicit "this" parameter, something such as the following:
public class Foo {
public void FooMethod(Foo this) { // do thing }
}
I doubt the above sample is how you would formally expose the hidden "this" parameter. How is this properly done?
Third:
A static method.
All clear, no problems here.
Fourth:
A static method and a target object assignable to the first parameter of the method. (emphasis mine)
Similar to my first question, what is the target object assignable to the first parameter. Syntactically, what would that look like?
Lastly:
When a delegate represents an instance method closed over its first argument (the most common case), the delegate stores a reference to the method's entry point and a reference to an object, called the target, which is of a type assignable to the type that defined the method
What does it mean by "an instance method closed over its first argument".
Thank you!
With the following
Foodefinition used:This means that delegate represents invokable instance function with "captured" instance. For example:
No, it means that since basically instance methods have implicit
thisparameter (the "hidden" one) you can create an open instance delegate (representing function with first parameter of the instance type):This is similar to the previous one. You use a static function with a single parameter to create a delegate representing function with no parameters by closing it over some target:
It means that the
new Foo()in first example is captured by the delegate instance, hence if the instance goes out of the visibility scope but the delegate does not, the instance would not be garbage collected so the delegate can be invoked correctly. I.e. creating a so called closure.