#385 – A Delegate Instance Can Refer to Both Instance and Static Methods
August 9, 2011 Leave a comment
A delegate instance in C# can refer to one or more methods that all have a particular signature. You can assign a single method to the delegate using the assignment (=) operator. You can also add or remove methods from the delegate’s invocation list using the addition assignment (+=) and subtraction assignment (-=) operators.
The delegate can refer to both instance and static methods. Internally, the delegate will store a reference to either a static method or to an instance method as well as the specific object to invoke the instance method on.
public delegate void StringDelegate(string s); static void Main() { // First method on invocation list--instance method Dog kirby = new Dog("Kirby"); StringDelegate del = kirby.Bark; // 2nd method on invocation list--static method del += LogABark; // Invoke methods on invocation list--both static and instance methods in this case del("Growf!"); } static void LogABark(string bark) { Console.WriteLine("Logging bark [{0}]", bark); }