CSharp - Delegate Instance and Static Method Targets


When an instance method is assigned to a delegate object, the delegate must maintain references to the method and to the type instance.

System.Delegate class's Target property represents this instance.

Target property is null when a delegate is referencing a static method.

System.Delegate class's Method property represents the method.

For example:


using System;
delegate void ProgressReporter (int percentComplete);

class Test//  w  ww  .j  a  v  a2  s .  c  o  m
     static void Main()
         X x = new X();
         ProgressReporter p = x.InstanceProgress;
         p(99);                                 // 99
         Console.WriteLine (p.Target == x);     // True
         Console.WriteLine (p.Method);          // Void InstanceProgress(Int32)

class X
       public void InstanceProgress (int percentComplete)
            => Console.WriteLine (percentComplete);