Exploring Delegates

An Example

If you like you may delete hidebysig and everything will still working. Do not delete anything else. First argument supplied to .ctor is instance of the class that defines the target method and second is pointer to the method to be called. Following is more in conformance with materials available from Microsoft:

    .method public specialname rtspecialname 
    instance void .ctor(object Instance, void * Method) runtime managed

    {
    } // end of method WildCard::.ctor

    .method public virtual instance int32 
    Invoke() runtime managed
    {
    } // end of method WildCard::Invoke


Type of Invoke must match type of method to be called, also list of parameters and their respective types must match. BeginInvoke must be of return type System.IAsyncResult. It accepts three parameters:the first is the same as that being used to call Invoke, type of second is System.AsyncCallback and third is the same as first parameter from .ctor. EndInvoke returns and accepts the same as Invoke plus one extra parameter of type System.IAsyncResult. Now we have all the definitions. Since we are planning to use debugger create shortcut in your “SendTo” folder and point it to "C:\Program Files\Microsoft.NET\FrameworkSDK\GuiDebug\DbgCLR.exe".
As always we will first write some code in high level language and disassemble P.E. to see what is going on. Save following as example.cs:

using System;
delegate int WildCard();
class Worker
{
    int m_w;
    public Worker(int w)
    {
        m_w=w;
    }
    public int Multiply()
    {
        return 2*m_w;
    }
}
class User
{
    public static void Main()
    {
        int c=2;
        Worker w=new Worker(c);
        WildCard v=new WildCard(w.Multiply);
        Console.WriteLine("Argument is {1}\nResult is {0}",v(),c);
    }
}

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Perl - The only language that looks the same before and after RSA encryption.” - Keith Bostic