Exploring Delegates

Running the example

Compile it from command line using “csc example.cs /debug”. Executing example.exe from command line should produce:

    Argument is 2
    Result is 4

Right click example.exe and from “Send To” pick “DbgCLR.exe”. Microsoft CLR Debugger will appear without any code loaded. Press F11 to step through code and example.cs will show up. 



Microsoft CLR Debugger in action

If you don’t have Command Window activate it from View->Other Windows menu. To see Disassembly you can right click on code window and select “Go To Disassembly” or customize debug toolbar. Command Window works very much as Immediate window from VB 6. Typing c=2 and pressing enter will set value of c or typing ?c and pressing enter will retrieve value of c into Command Window. Pressing F11 step through code and if you like observe changes in Locals window.
Next we will send example.exe to ILDASM using the same trick described in my article “Modest introduction to IL assembly language”. If we dump treeview this is what we get:

    ___[MOD] C:\Documents and Settings\current\My Documents\asm\finale\example.exe
    | M A N I F E S T
    |___[CLS] User
    | | .class private auto ansi beforefieldinit 
    | |___[MET] .ctor : void()
    | |___[STM] Main : void()
    |
    |___[CLS] WildCard
    | | .class private auto ansi sealed 
    | | extends [mscorlib]System.MulticastDelegate 
    | |___[MET] .ctor : void(object,native int)
    | |___[MET] BeginInvoke : class [mscorlib]System.IAsyncResult(class [mscorlib]System.AsyncCallback,object)
    | |___[MET] EndInvoke : int32(class [mscorlib]System.IAsyncResult)
    | |___[MET] Invoke : int32()
    |
    |___[CLS] Worker
    | | .class private auto ansi beforefieldinit 
    | |___[FLD] m_w : private int32
    | |___[MET] .ctor : void(int32)
    | |___[MET] Multiply : int32()
    |


Please note that our target Worker.Multiply is not receiving any parameter so parameter list for Invoke, BeginInvoke and EndInvoke is shorter than usual. Now dump code as dis_example and compile it from command line using “ilasm dis_example /deb”. Send dis_example.exe to DbgCLR.exe and press F11. This time dialog box will appear asking you to locate dis_example.il. After pointing to location of dis_example.il debugger will load our file and pressing F11 we can examine flow of program checking from time to time Locals and values in Command Window.


Locals window towards end of program

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.

“The difference between theory and practice is smaller in theory than in practice.”