3

I tried digging into delegate class for declaration of Invoke method but i did not found it!. Where is it exactly?!!

To check this condition copy this code:

public class Program
{
    public delegate void LogDel(string msg);
    private static void Main(string[] args)
    {
        var logger = new LogDel(Logger);
        var msg = "hi";
        logger.Invoke(msg);
        logger(msg);
    }
    public static void Logger(string logMsg)
    {
        Console.WriteLine(logMsg);
    }
}
Reza ArabQaeni
  • 4,848
  • 27
  • 46
  • Check this out: http://stackoverflow.com/questions/25095709/where-exactly-is-somedelegate-invoke-implemented-and-how-is-it-wired-to-the-de, http://stackoverflow.com/questions/6388466/how-does-delegate-invoke-work, http://stackoverflow.com/questions/14961450/where-are-clr-defined-methods-like-delegate-begininvoke-documented – Bojan Komazec Aug 24 '14 at 07:39
  • From the [docs](http://msdn.microsoft.com/en-us/library/system.delegate(v=vs.110).aspx) for System.Delegate: "The common language runtime provides an Invoke method for each delegate type, with the same signature as the delegate. You do not have to call this method explicitly from C#, Visual Basic, or Visual C++, because the compilers call it automatically. The Invoke method is useful in reflection when you want to find the signature of the delegate type." – Mike Zboray Aug 24 '14 at 08:06

1 Answers1

3

When you create a delegate, the compiler at compile time generates a class inheriting from MulticastDelegate, adding three methods to the class: BeginInvoke, EndInvoke and Invoke. You can easily see it using using ILSpy and the likes.

That is why you cant see it while looking in the Delegate class

This is what MSDN has to say:

MulticastDelegate is a special class. Compilers and other tools can derive from this class, but you cannot derive from it explicitly. The same is true of the Delegate class.

In addition to the methods that delegate types inherit from MulticastDelegate, the common language runtime provides two special methods: BeginInvoke and EndInvoke.

A MulticastDelegate has a linked list of delegates, called an invocation list, consisting of one or more elements. When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order in which they appear. If an error occurs during execution of the list then an exception is thrown

Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321