Solution 1 is only good for static methods. Yes, you asked about static methods, but this is not the only possibility. But this is also possible with the class instance. Compare:
delegate int SomeDelegate(int i);
class Implementation {
internal int SomeMethod(int i) { return i; }
internal static int SomeOtherMethod(int i) { return i; }
}
class ImplementationUsage {
internal void Demo() {
SomeDelegate theDelegateInstance = Implementation.SomeOtherMethod;
theDelegateInstance(3);
Implementation implementation = new Implementation();
theDelegateInstance = implementation.SomeMethod;
theDelegateInstance(4);
}
}
Pay attention that I completely removed
new SomeDelegate(/* ... */);
this is a totally redundant expression, in this case (and original MSDN documentation is probably not clear about it).
Also, you don't have to declare delegate
int SomeDelegate(int i);
instead, you can use already available declaration based on the set of
System.Func
generic declarations:
System.Func<int, int>
.
The delegate instance class (not to be confused with delegate type) is such a structure which can carry two references: to the method to be called, and to the instance of the type implicitly passed to this method at the moment of the call. In fact, this is much more advanced type, which is pretty hard to explain in all detail. For some, please see the corresponding section of my article, "4.1 On the Nature of Delegate Instance":
Dynamic Method Dispatcher[
^].
It's worth mentioning that another, very useful way of implementing delegates is using
anonymous methods. You have to know them well due to multiple benefits of them, especially for event handling, but also many other cases. (I'll gladly answer if you have any questions on them.)
—SA