<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://community.bartdesmet.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>B# .NET Technical Community Homepage</title><link>http://community.bartdesmet.net/blogs/</link><description>Bart De Smet's online technical community</description><dc:language>en-US</dc:language><generator>CommunityServer 2007 (Build: 20423.869)</generator><item><title>Four books to pre-order</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/09/01/four-books-to-pre-order.aspx</link><pubDate>Tue, 02 Sep 2008 00:19:59 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13950</guid><dc:creator>bart</dc:creator><slash:comments>3</slash:comments><description>&lt;p&gt;I love technical books and it&amp;#39;s hard to resist the temptation buying new ones :-). This fall is especially difficult with four great titles coming up:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;The C# Programming Language (3rd Edition)&lt;/strong&gt; by Anders Hejlsberg, Mads Torgersen, Scott Wiltamuth, Peter Golde (978-0321562999)      &lt;br /&gt;      &lt;br /&gt;The entire language specification for C# 3.0 in book format. Yes, I know you can download the whole thing from MSDN (and that has been a common critique on the previous editions) but the new edition has tons of annotations interwoven with the specification to clarify the technicalities. Don&amp;#39;t expect much samples or how-to&amp;#39;s though; it&amp;#39;s a specification reference in the first place (and that&amp;#39;s the sort of thing I love).      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Windows Internals: Including Windows Server 2008 and Windows Vista, Fifth Edition&lt;/strong&gt; by Mark Russinovich and David Solomon (978-0735625303)      &lt;br /&gt;      &lt;br /&gt;In my opinion a must-read cover-to-cover for every developer targeting the Windows platform. Sure enough, there will be chapters that are no more exciting than watching wet paint dry, but if you really want to know how the Windows OS is structured and how it all woks, this is the book to check out. Since its previous release it has grown over 200 pages with exciting new Vista/2008 Server stuff. Looking forward to it.      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Concurrent Programming on Windows &lt;/strong&gt;by Joe Duffy (978-0321434821)      &lt;br /&gt;      &lt;br /&gt;With the new challenges arising from the multi/many-core wave, the art of writing concurrent applications has never been more important to master. This book explains the fundamentals of concurrent application development, best practices and more, targeting the Windows platform. Joe&amp;#39;s been working on various concurrency APIs ranging from the .NET 2.0 thread pool to the Parallel Extensions to the .NET Framework.      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition)&lt;/strong&gt; by Krzysztof Cwalina and Brad Abrams (978-0321545619)      &lt;br /&gt;      &lt;br /&gt;&amp;quot;Do, Don&amp;#39;t, Consider and Avoid&amp;quot; are the four keywords of this book. If you want to learn how to structure and write reusable .NET libraries, there&amp;#39;s no better book to look for than this one. With lots of annotations on applications within Microsoft by various architects, the book is not only a must-have reference, it&amp;#39;s also well-suited to read cover-to-cover in a few evenings.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;What I&amp;#39;m currently reading? Various papers on theoretical stuff, refreshing my &amp;quot;denotational mind&amp;quot; and a recently-released book on &amp;quot;&lt;strong&gt;Design Concepts in Programming Languages&lt;/strong&gt;&amp;quot; by Franklyn Turbak and David Gifford (978-0262201759). Quite heavy stuff (literally) but definitely a great reference for a more formal coverage of programming languages.&lt;/p&gt;  &lt;p&gt;Have a fun time reading!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13950" width="1" height="1"&gt;</description></item><item><title>C# 3.0 Query Expression Translation Cheat Sheet</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/30/c-3-0-query-expression-translation-cheat-sheet.aspx</link><pubDate>Sat, 30 Aug 2008 08:29:05 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13937</guid><dc:creator>bart</dc:creator><slash:comments>7</slash:comments><description>&lt;p&gt;As a reference for some planned and unplanned future posts, I wanted to share out my “cheat sheet” for the C# 3.0 translation carried out for query expressions. Obviously it’s based on the &lt;a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc"&gt;C# 3.0 Language Specification&lt;/a&gt; more specially section 7.15.2. A few remarks that deserve more attention when reading the specification:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Words in &lt;strong&gt;bold&lt;/strong&gt; are &lt;em&gt;contextual &lt;/em&gt;keywords; these are &lt;u&gt;not&lt;/u&gt; reserved keywords as the language doesn’t introduce new reserved keywords to ensure forward compatibility for programs written in previous language versions (e.g. “from” could be used as a variable name).&lt;/li&gt;    &lt;li&gt;Method names indicated in &lt;font color="#ff0000"&gt;red&lt;/font&gt; are the query operators known by the compiler as compilation targets for the corresponding query syntax &lt;em&gt;contextual &lt;/em&gt;keywords. Where these methods come from is purely a question answered by method resolution rules, obviously including extension methods from C# 3.0 on.&lt;/li&gt;    &lt;li&gt;The ‘*’ in the translations below stands for the transparent identifier, more of an implementation aspect of the compiler to “carry forward” the range variables captured in the anonymous type produced by a query operation (e.g. in SelectMany). This illustrates that anonymous types (as well as lambda BLOCKED EXPRESSION are essential pieces of glue to make LINQ work (although alternatives based on a hypothetical “tuple type” runtime feature would work too).&lt;/li&gt;    &lt;li&gt;For the orderby operator, corresponding flavors with descending order have been omitted. Essentially all of the ordering clauses can optionally have the descending keyword, resulting in an OrderByDescending or ThenByDescending call in the corresponding translation.&lt;/li&gt;    &lt;li&gt;All the rules are mutually recursive: starting with a query expression, the translation will gradually “compile away” certain parts of the query expression syntax into method call driven equivalent expressions. Notice all rules without an ellipsis … on the left-hand side don’t have any query expression keywords left on the right-hand side – these are the terminal “closed” expressions that are entirely expressible in C# 3.0 \ { LINQ }. It’s like peeling off the LINQ layer from the C# 3.0 onion.&lt;/li&gt;    &lt;li&gt;The first two rules for Select seem redundant, i.e. when substituting v for x in the second rule one gets the first rule. The reason they are spelled out each individually is because the first rule covers degenerate expressions (covered in &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/20/what-do-vb-9-0-error-bc36593-expression-of-type-x-is-not-queryable-and-c-3-0-error-cs1936-could-not-find-an-implementation-of-the-query-pattern-for-source-type-x-really-mean.aspx"&gt;another post&lt;/a&gt; of mine) and rules should be evaluated from top to bottom. The Select ( x =&amp;gt; x ) is kept based on the conditions spelled out in section 7.15.2.3.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So here’s my cheat sheet:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/C3.0QueryExpressionTranslationCheatSheet_14DA/image.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="863" alt="image" src="http://www.bartdesmet.info/images_wlw/C3.0QueryExpressionTranslationCheatSheet_14DA/image_thumb.png" width="1178" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Feel free to redistribute it in any form but I’d appreciate at least a reference to the official &lt;a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc"&gt;C# 3.0 Language Specification&lt;/a&gt; with it as that’s the ultimate resource for the detailed language specifics. A pointer to my blog would be much appreciated as well of course :-).&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13937" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Intermezzo: SOS in Visual Studio</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/29/to-bind-or-not-to-bind-dynamic-expression-trees-intermezzo-sos-in-visual-studio.aspx</link><pubDate>Fri, 29 Aug 2008 10:05:16 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13929</guid><dc:creator>bart</dc:creator><slash:comments>5</slash:comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Last time we talked about dealing with dynamic code generation using Reflection.Emit to generate calls to our dynamic binder. I’ve shown how to see the IL that gets generated by means of the Dynamic IL Visualizer add-in in Visual Studio. In this post I want to point out that you can actually live without that visualizer and go the &lt;strong&gt;hard-core way using SOS&lt;/strong&gt;, aka “Son of Strike”, the WinDbg extension for managed code debugging that ships with the .NET Framework (sos.dll). A little-known fact is that SOS can be loaded directly in Visual Studio through the Immediate Window.&lt;/p&gt;  &lt;p&gt;&lt;u&gt;Note:&lt;/u&gt; This post is screenshot-driven; to conserve bandwidth I’ve included only thumbnails in the post itself; “click to enlarge” is the message.&lt;/p&gt;  &lt;p&gt;&lt;u&gt;Note:&lt;/u&gt; There are many ways to get to the information you care about; in the end we’re dealing with object graphs. This post is more an exploration of the data that you can get at if you want to do so; the various paths to get there are more a matter of style (in physical terms: the potential energy is constant, but the accumulated kinetic energy corresponding to the developer’s finger muscle contractions when dealing with the keyboard may vary).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 1 – Loading SOS&lt;/h1&gt;  &lt;p&gt;We’re on a breakpoint in managed code and will try to load SOS through the Immediate Window using &lt;em&gt;.load sos&lt;/em&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;For this to work, &lt;u&gt;native&lt;/u&gt; code debugging needs to be enabled in the project properties:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_3.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="176" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_3.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 2 – Finding dynamic methods&lt;/h1&gt;  &lt;p&gt;To find the dynamically generated methods, we can search the heap for objects of type DynamicMethod using &lt;em&gt;.dumpheap DynamicMethod&lt;/em&gt;. As you can see we don’t have any yet:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_4.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_4.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Using F10 we step to the next method, executing Compile causing the dynamic method for the expression to be compiled. Rerunning the command now yields:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_5.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_5.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We’re in business. As you can see we had two matching types: DynamicMethod and DynamicMethod+RTDynamicMethod. We’re interested in the former one, so we follow the MT field back to the list of objects. MT stands for Method Table which is a runtime structure describing the object layout for a particular type. It can be used to locate fields and methods in preparation to calls. If you want, you can use &lt;em&gt;!dumpmt –MD &amp;lt;MT address&amp;gt;&lt;/em&gt; to dump such a table; this will show all of the “methods in the table”.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 3 – Dumping the IL&lt;/h1&gt;  &lt;p&gt;Now that we have the DynamicMethod object, we can dump the IL for it using &lt;em&gt;!dumpIL &amp;lt;object address&amp;gt;&lt;/em&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_6.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_6.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As we were compiling the identity function I, the IL shown should just be a ldarg.0 and sure it is.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 4 – Another sample&lt;/h1&gt;  &lt;p&gt;We could have stopped with the previous sample but our dynamic dispatch is interesting to analyze too. Breaking after our Substring sample compilation (in a fresh run, so that the old DynamicMethod is no longer displayed) results in:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_7.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_7.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We can follow it through to the IL again:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_8.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_8.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice the call to “something in parentheses”. This is the runtime token representing the method, which we can dump using &lt;em&gt;!do &amp;lt;address&amp;gt;&lt;/em&gt;. In addition, &lt;em&gt;!dumpIL&lt;/em&gt; hints at dumping the token array:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_9.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_9.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The result of doing so is an array of tokens used in the IL stream. I’ll show this in a second but you might wonder what those fancy numbers in the IL stream like “70000002” stand for. Those indicate token types as defined in CorTokenType (see corhdr.h, for instance in the SSCLI “Rotor” distribution). To find the token type, mask with 0xFF000000, so in our sample that leaves 0x&lt;strong&gt;70&lt;/strong&gt;000000 and this is defined as mdtString. The remainder (mask with 0x00FFFFFF) leaves us with the RID (relative ID) of 0x0000000&lt;strong&gt;2&lt;/strong&gt;, so entry two in the table contains the corresponding token value:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_10.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_10.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;And yes, we see “Substring” appearing. Similarly value 2000003 in IL_0010 gives us a type def token (for System.Object) at offset 3 and value 0a000004 in IL_0031 gives us a member ref token (for our DynamicBinder.Call method) at offset 4. For the latter one, the debugger output gives you the indirection in between parentheses straight away:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_11.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_11.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;How convenient!&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 5 - From token to MethodInfo to DeclaringType&lt;/h1&gt;  &lt;p&gt;Next we can follow the object chains all the way up to the declaring type: first we get from the token to the method it represents and second we can traverse m_declaringType to get the corresponding type:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_12.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_12.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This produces a System.RuntimeType instance containing a Method Table reference:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_13.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_13.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So we can dump the method table with &lt;em&gt;!dumpmt –MD &amp;lt;MT address&amp;gt;&lt;/em&gt; as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_14.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_14.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As you can see we’re in our DynamicBinder class.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 6 – What about the signature?&lt;/h1&gt;  &lt;p&gt;Instead of following the path to the m_declaringType above, we could follow the m_signature as well:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_15.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;System.Signature wraps a m_signature field of type SignatureStruct which we can dump as well, but as this is a value type we can’t use &lt;em&gt;!do&lt;/em&gt; but rather need to use &lt;em&gt;!dumpvc&lt;/em&gt; (standing for value class) passing in the method table (otherwise the debugger wouldn’t know how to interpret the struct which is simply a blob of data) and the address.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 7 – And back to the method being called&lt;/h1&gt;  &lt;p&gt;From the signature struct we can reach out to the method represented by the signature through m_pMethod. This is a runtime handle, wrapping an IntPtr pointer to where the loaded IL code lives. In other words, we can invoke dumpIL on that address to see the contents of what turns out to be our DynamicBinder.Call method:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_16.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_15.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;(Notice the closure classes in the IL generated because of our C# 3.0 lambda expressions embedded in the LINQ query we use for method overload resolution.)&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 8 – Dynamic modules&lt;/h1&gt;  &lt;p&gt;Dynamic methods live in dynamic modules, so it would be interesting to see those. SOS comes to the rescue with &lt;em&gt;!dumpdomain&lt;/em&gt;.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_17.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_16.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Scroll down a bit and we get to see the dynamic modules. With some poking around it turns out that the last one is the one we’re looking for as it contains a multicast delegate, precisely what we&amp;#39;ve been generating. We can visualize it using &lt;em&gt;!dumpmodule –mt&lt;/em&gt; &lt;em&gt;&amp;lt;address&amp;gt;&lt;/em&gt; also showing the types that are referenced inside the module (that’s where we see the MulticastDelegate).&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_18.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_17.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Also notice the attribute saying “Reflection”. To see how the type definition (TypeDef) is indirected through a method table map (MethodTableMap), follow the arrows below. Green indicates the indexing and again the masked first two bytes of the green value indicate the CorTokenType, in this case a TypeDef. You can do the same exercise for the TypeRef (0x01000000) – follow the memory pointer and get the first (zero-based count obviously) element referred in there (it should read 24 e5 0f 79 as you can infer from the output produced by the debugger, considering little endian conversion).&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_19.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_18.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Unfortunately the defined type is marked as unloaded so we’re at a dead end – feel free to explore the Method Table for the type a bit further. In a similar way you can track down the loaded module with our DynamicBinder to do some explorations (also starting from &lt;em&gt;!dumpdomain&lt;/em&gt;):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_20.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_19.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Dumping the binder’s method table gives us:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_21.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_20.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Who still needs ILDASM or Reflector? :-)&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 9 – Walking the stack&lt;/h1&gt;  &lt;p&gt;To finish this post, I’d like to show how to dump the stack objects using &lt;em&gt;!dso&lt;/em&gt; to get to some of this information through yet an alternative route:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_22.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_21.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In green I’ve indicated the result of the dynamic call and what it corresponds to. However, the items in red indicate our (mysterious?) unloaded type once more. As you’ll see though, the IL is still available:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_23.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_22.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The result is predictable by now I guess.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13929" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 3</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/28/to-bind-or-not-to-bind-dynamic-expression-trees-part-3.aspx</link><pubDate>Thu, 28 Aug 2008 17:35:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13925</guid><dc:creator>bart</dc:creator><slash:comments>5</slash:comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Last time in this series we were able to compile a stunningly complex “dynamic lambda” x =&amp;gt; x – also known as I in the world of combinators – into IL code at runtime. As that’s not particularly useful, we want to move on to slightly more complex expressions like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;o = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;o&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;call = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Call(o, &lt;span style="color:#a31515;"&gt;&amp;quot;Substring&amp;quot;&lt;/span&gt;, a, b);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;func = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(call, o, a, b);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 1, 2));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Or, in pretty print,&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(o, a, b) =&amp;gt; o.Substring(a, b)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Setting the scene&lt;/h1&gt;

&lt;p&gt;We explained how the translation of a dynamic expression tree takes place in general: as we traverse the tree, individual nodes are visited asking them to append code capturing the expression’s semantics to an IL stream, pushing a value on the stack that corresponds to the evaluated expression. The method that does this translation for every dynamic expression is called “Compile”:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Appends IL instructions to calculate the expression&amp;#39;s runtime value, putting it on top of the evaluation stack.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;ilgen&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;IL generator to append to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;ldArgs&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Lambda argument mappings.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;protected internal abstract void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;In here we’re using a simplified concept of “lambda parameters in scope” using &lt;em&gt;ldArgs&lt;/em&gt;, avoiding getting into slightly more complex techniques such as hoisting that are required for more involved expression trees. Previously you saw how to implement this method for ParameterDynamicExpression and LambdaDynamicExpression, respectively:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!ldArgs.ContainsKey(&lt;span style="color:blue;"&gt;this&lt;/span&gt;))
        &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Parameter expression &amp;quot; &lt;/span&gt;+ Name + &lt;span style="color:#a31515;"&gt;&amp;quot; is not in scope.&amp;quot;&lt;/span&gt;);

    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg, ldArgs[&lt;span style="color:blue;"&gt;this&lt;/span&gt;]);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;and&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
{
    Body.Compile(ilgen, ldArgs);
    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ret);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Dynamic method calls and binders&lt;/h1&gt;

&lt;p&gt;For MethodCallExpression things are a bit more involved than for the expression types above. Before we start, remember the most important portion of the Compile method contract: leave one value on top of the stack that corresponds to the evaluated expression, in this case a method call. What does a method call consist of? Here are the ingredients:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;&amp;gt; Arguments { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;Object { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
&lt;span style="color:blue;"&gt;public string &lt;/span&gt;Method { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;As we’re seeing other DynamicExpression objects being referenced in here, it’s already clear we’ll have to evaluate those by recursively calling Compile. So, we could do something along the lines of:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;compile Object 
    &lt;br /&gt;foreach argument in Arguments 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; compile argument 

    &lt;br /&gt;call Method&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That’s the typical structure of a call site, pushing arguments on the stack including the object to invoke the method on. From a stack point of view: n + 1 arguments are pushed, where n is the number of arguments and 1 accounts for the instance to invoke the method one, and next all of those stack citizens are eaten by the method call, producing the single return value on top of the stack. This follows the contract of our Compile method.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;There’s a slight problem though: we can’t emit the call because we don’t know what type to invoke it one. The reason is well-known in the meantime: the Object nor the Arguments have strongly-typed information, so just given a string named “Method”, we can’t get the required method metadata to emit a call(virt) instruction. Bummer. But that’s the whole point of dynamic programming, delaying the decision about the executed method/function till runtime because the type might dynamically grow with new members (think of ETS in PowerShell as a sample of such a capability).&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;One way to solve this problem is to emit a bunch of reflection code to investigate the type of Object at runtime, do the same for all of the arguments, try to find a suitable method to call, etc etc. I shouldn’t explain how complicated this would become :-). There are lots of drawbacks to this: we’re baking in the whole dynamic call infrastructure into the call site and as we’re emitting all of that code, the odds to adapt it without having to recompile the code are off. This whole “locate a suitable method” algorithm could be made extensible too if we’re not emitting it into the generated code straight away. In other words, we want to get out of the IL generating business as soon as we can, and introduce a level of indirection. That particular kind of indirection is what we call a &lt;strong&gt;binder&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;So what’s a binder precisely? It’s simply a class that contains all the functionality to make well-formed decisions (based on certain desired semantics) about method calls (amongst other invocation mechanisms). Actually we have such a thing in the framework already: &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.binder.aspx"&gt;System.Reflection.Binder&lt;/a&gt;. As the documentation says:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Selects a member from a list of candidates, and performs type conversion from actual argument type to formal argument type.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The list of candidates is something that can be made extensible, allowing methods to be “imported” or “attached” to existing types at runtime. The type conversion clause in the sentence above outlines that the binder is responsible to take the actual passed in arguments (in our case weakly typed) and turn them into (i.e. casting) formal argument types that are suitable for consumption by the selected candidate method. The sample on MSDN for &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.binder.aspx"&gt;System.Reflection.Binder&lt;/a&gt; shows what it takes to implement such a beast. We’re not going to do that though, just to simplify matters a bit. As we’re only interested in method calls, we’ll just implement the bare minimum binder to get the job done and explained. Furthermore, we won’t spend time on implicit conversions for built-in types (like int to long) as the mentioned sample illustrates that already. Last but not least, generics are not brought in the equation either.&lt;/p&gt;

&lt;p&gt;Without further delay, let’s show a possible binder implementation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicBinder
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static object &lt;/span&gt;Call(&lt;span style="color:blue;"&gt;object &lt;/span&gt;@this, &lt;span style="color:blue;"&gt;string &lt;/span&gt;methodName, &lt;span style="color:blue;"&gt;params object&lt;/span&gt;[] args)
    {
        &lt;span style="color:green;"&gt;//
        // Here we&amp;#39;re going to be lazy for demo purposes only. Our overload resolution
        // will pick the first applicable method without applying &amp;quot;betterness&amp;quot; rules
        // as outlined in the C# specification (v2.0, section $7.4.2). We don&amp;#39;t care
        // about extension methods either (how could the namespace be brought in scope
        // in the context of an expression tree...?) nor other dynamic type extensions
        // such as IExpando (~ IMarshalEx) or e.g. PowerShell ETS.
        //

        &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;result = (&lt;span style="color:blue;"&gt;from &lt;/span&gt;method &lt;span style="color:blue;"&gt;in &lt;/span&gt;@this.GetType().GetMethods()
                      &lt;span style="color:blue;"&gt;where &lt;/span&gt;method.Name == methodName
                      &lt;span style="color:blue;"&gt;let &lt;/span&gt;parameters = method.GetParameters()
                      &lt;span style="color:blue;"&gt;where &lt;/span&gt;parameters.Length == args.Length
                            &amp;amp;&amp;amp; parameters.Where((p, i) =&amp;gt; p.ParameterType.IsAssignableFrom(args[i].GetType())).Count() == args.Length
                      &lt;span style="color:blue;"&gt;select new &lt;/span&gt;{ Method = method, Parameters = parameters }).SingleOrDefault();

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(result == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        {
            &lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StringBuilder&lt;/span&gt;();
            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;Failed to bind method call: &amp;quot;&lt;/span&gt;);
            sb.Append(@this.GetType());
            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;);
            sb.Append(methodName);
            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;(&amp;quot;&lt;/span&gt;);

            &lt;span style="color:blue;"&gt;int &lt;/span&gt;n = args.Length;
            &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; n; i++)
                sb.Append(args[i].GetType().ToString() + (i != n - 1 ? &lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot; &lt;/span&gt;: &lt;span style="color:#a31515;"&gt;&amp;quot;&amp;quot;&lt;/span&gt;));

            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;).&amp;quot;&lt;/span&gt;);
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(sb.ToString());
        }

        &lt;span style="color:blue;"&gt;return &lt;/span&gt;result.Method.Invoke(@this, args);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;This needs some explanation I assume. The signature should be straightforward: given an object &lt;em&gt;@this&lt;/em&gt;, we want to call method &lt;em&gt;methodName&lt;/em&gt; with zero or more arguments &lt;em&gt;args&lt;/em&gt;. The result of this will be an &lt;em&gt;object&lt;/em&gt; again (notice we don’t support void return types for methods being called, which isn’t too big of deal when considering &lt;em&gt;functions&lt;/em&gt; as lambdas – i.e. no statement lambdas). What’s more interesting though is the way we find a suitable method. I chose to write it as a gigantic LINQ expression just to show how powerful LINQ can be. Let me walk you through it:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;result = (&lt;span style="color:blue;"&gt;from &lt;/span&gt;method &lt;span style="color:blue;"&gt;in &lt;/span&gt;@this.GetType().GetMethods()
              &lt;span style="color:blue;"&gt;where &lt;/span&gt;method.Name == methodName
              &lt;span style="color:blue;"&gt;let &lt;/span&gt;parameters = method.GetParameters()&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;For all methods available on the left-hand side of the call (i.e. &lt;em&gt;@this&lt;/em&gt;) select those methods that have the same name (case sensitive compare – this would be a binder that mimics C# name resolution for method calls) and let &lt;em&gt;parameters&lt;/em&gt; be a variable containing the parameters for each of the selected methods going forward. In other words, in what follows we’re seeing a sequence of &lt;em&gt;(method, parameters)&lt;/em&gt; pairs mapping each suitable (at least concerning the name) method on the parameters it takes. Next we need to do overload resolution:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;              where &lt;/span&gt;parameters.Length == args.Length&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we make sure the number of arguments on the candidate method matches the number of arguments passed in to the binder’s Call call. This implies we don’t consider things like optional arguments supported by some languages which would mean that having less matching parameters (but not more!) would keep the method as a candidate, although there would need to be some ordering to make sure that methods with more arguments take precedence over methods with arguments supplied through optional values. Notice this simple check makes it also impossible to call a “params” method without stiffing the argument in an array upfront.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;                    &amp;amp;&amp;amp; parameters.Where((p, i) =&amp;gt; p.ParameterType.IsAssignableFrom(args[i].GetType())).Count() == args.Length&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now we’re in the clause that’s maybe the most interesting. Here we’re taking all the parameters of the candidate and check that the parameter &lt;em&gt;p &lt;/em&gt;on position &lt;em&gt;i&lt;/em&gt; has a type that’s assignable from the type of the argument passed in to the binder’s Call method. In essence this is &lt;em&gt;contravariance&lt;/em&gt; for arguments. Assume we’re examining a candidate method like this:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;class ExperimentalZoo 
    &lt;br /&gt;{ 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Animal CloneBeast(Mammal g); 

    &lt;br /&gt;}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and we’re calling the binder as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;DynamicBinder.Call(new ExperimentalZoo(), “CloneBeast”, new Giraffe())&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As we’re calling the binder with an argument of type Giraffe (args[0].GetType()) and Giraffe inherits from Mammal (parameters[i].ParameterType), the candidate is compatible. However, if we’d call the method with an argument of type Goldfish it would clearly not be compatible (as a fish is not a mammal). This is precisely what the Where clause above enforces. The Count() == args.Length trick at the end makes sure all of the arguments pass the test (using the All operator would be ideal but it hasn’t an overload passing in the index; alternatively a Zip operator would be beneficial too).&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Finally we have the select clause:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;              select new &lt;/span&gt;{ Method = method, Parameters = parameters }).SingleOrDefault();&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;which simply extracts the method (of type MethodInfo) and the parameters (of type ParameterInfo[]) and makes sure we only found one match. This is another simplification for illustrative purposes only – to be fully compliant with e.g. the C# language, we’d have to implement all of the overload resolution rules including “betterness rules” that select the most optimal overload. More information on this can be found in the C# specification, in v3.0 under “7.4.3 Overload Resolution”. The key takeaway though is that we can tweak this binder as much as we want (e.g., left as an exercise, we could implement resolution that takes extension methods into account) without affecting the generated IL code that will simply call into the binder’s Call method.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;If we find one result, we can just go ahead and call it by calling through the retrieved Method using the Invoke method, passing in the &lt;em&gt;@this&lt;/em&gt; pointer and the &lt;em&gt;args&lt;/em&gt; array.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Connecting the pieces&lt;/h1&gt;

&lt;p&gt;Now that we have our beloved binder, we need to glue it together with our dynamic expression compilation. In concrete terms this means we need to emit a call to DynamicBinder.Call in the generated IL for the DynamicCallExpression. This isn’t too hard either:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(Object == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldnull);
    &lt;span style="color:blue;"&gt;else
        &lt;/span&gt;Object.Compile(ilgen, ldArgs);

    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldstr, Method);

    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldc_I4, Arguments.Count);
    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Newarr, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;));

    &lt;span style="color:#2b91af;"&gt;LocalBuilder &lt;/span&gt;arr = ilgen.DeclareLocal(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;[]));
    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Stloc, arr);

    &lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0;
    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;arg &lt;span style="color:blue;"&gt;in &lt;/span&gt;Arguments)
    {
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldloc, arr);
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldc_I4, i++);
        arg.Compile(ilgen, ldArgs);
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Stelem_Ref);
    }

    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldloc, arr);

    ilgen.EmitCall(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Call, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;DynamicBinder&lt;/span&gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Call&amp;quot;&lt;/span&gt;), &lt;span style="color:blue;"&gt;null&lt;/span&gt;);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;What’s going on here? First, we check whether an Object has been specified. This is more of an extensibility point in case our binder would like to implement &lt;em&gt;global functions&lt;/em&gt; (also left as an exercise, for example you could recognize null.Add(1, 2) as a global Add call, translating into Math.Add(…); or, the Method property could be set to “Math.Add” to denote a static method call). We’ll assume the else case holds true for our samples, causing us to call Compile recursively on the Object dynamic expression. This will add the value corresponding to the Object expression tree’s evaluation on top of the stack (note: you can smell call-by-value semantics already, don’t you?). Next, we load the string specified in the Method property onto the stack as well. Currently the stack looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(string) Method 
    &lt;br /&gt;(object) Object.Compile result&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now we get into interesting stuff as our binder’s Call method expects to see an object[] as its third parameter. How many arguments? On for each of the DynamicExpression objects in the Arguments collection, so we do &lt;em&gt;Newarr&lt;/em&gt; passing in the object type &lt;em&gt;object&lt;/em&gt; after pushing the number of elements to be allocated on the stack using &lt;em&gt;Ldc_I4&lt;/em&gt; passing in Arguments.Count. Now we have our array, we can store it in a local variable we call “arr”. Time to fill the array by first loading the local, then pushing the index followed by a push of the argument’s value – again obtained by a recursive Compile call on the argument “arg” – and finally calling &lt;em&gt;stelem_ref&lt;/em&gt; (as we’re dealing with System.Object we need _ref). The loop invariant is that it doesn’t change the stack height: it cleanly loads three “arguments” to stelem_ref which brings the stack delta back to 0).&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Ultimately, we load the array local variable and the stack looks like (semantically):&lt;/p&gt;

&lt;blockquote&gt;(object[]) Arguments.Select(arg =&amp;gt; arg.Compile()).ToArray() 
  &lt;br /&gt;(string) Method 

  &lt;br /&gt;(object) Object.Compile()&lt;/blockquote&gt;

&lt;p&gt;ready for a call to DynamicBinder.Call which turns the stack into:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(object) DynamicBinder.Call(Object.Compile(), Method, Arguments.Select(arg =&amp;gt; arg.Compile()).ToArray())&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Again, we have managed to keep the house clean with regards to the stack behavior, i.e. the element on top of the stack contains the value corresponding to the entire (MethodCall)DynamicExpression.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Testing it&lt;/h1&gt;

&lt;p&gt;Does it work? Let’s try with our running sample:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;o = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;o&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;call = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Call(o, &lt;span style="color:#a31515;"&gt;&amp;quot;Substring&amp;quot;&lt;/span&gt;, a, b);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;func = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(call, o, a, b);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 1, 2));&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Recognize the patterns in the output IL?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="602" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_thumb.png" width="914" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A quick walk-through:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;IL_0000 loads MethodCallDynamicExpression.Object which in turn was compiled into a ldarg V_0 by the ParameterDynamicExpression’s Compile method (this corresponds to “o”) &lt;/li&gt;

  &lt;li&gt;IL_0006 loads MethodCallDynamicExpression.Method &lt;/li&gt;

  &lt;li&gt;IL_000b to IL_0015 prepares the array for the method call arguments to be passed to the binder &lt;/li&gt;

  &lt;li&gt;IL_0016 to IL_0022 puts the first argument (corresponding to “a” translated into ldarg V_1 through ParameterDynamicExpression.Compile) in the array &lt;/li&gt;

  &lt;li&gt;IL_0023 to IL_002f does the same for the second argument (corresponding to “b” translated into ldarg V_2 through ParameterDynamicExpression.Compile) &lt;/li&gt;

  &lt;li&gt;IL_0030 to IL_0036 finally makes the call through the binder, passing in the results of the above and returning the value produced by the binder &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If we now set a breakpoint in the DynamicBinder.Call method and let execution continue, we’ll see:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_3.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="361" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_thumb_3.png" width="864" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The third line in the Call Stack is where DynamicInvoke is happening:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func.Compile().&lt;strong&gt;&lt;u&gt;DynamicInvoke&lt;/u&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 1, 2)&lt;/strong&gt;);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;and through the “External Code” corresponding to our emitted dynamic method we got back into the DynamicBinder that now will pick the right Substring method given lhs “Bart” and arguments 1 and 2. Ultimately the following prints to the screen:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_4.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="64" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_thumb_4.png" width="271" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Magic. To show it’s really extensible we can start to compose things endlessly with our two main ingredients: parameter and method call expressions. Here’s a sample (reverse engineering the nested DynamicExpression factory calls is left as an exercise):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_5.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="71" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_thumb_5.png" width="824" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Also left as an exercise to the reader is to find values for o and a through h that produce the displayed output above :-). For the record, here’s the corresponding IL:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;IL_0000: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_0 
    &lt;br /&gt;IL_0004: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0005: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0006: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;Replace&amp;quot; 

    &lt;br /&gt;IL_000b: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 2 

    &lt;br /&gt;IL_0010: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_0015: stloc.0&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0016: ldloc.0&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0017: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_001c: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_3 

    &lt;br /&gt;IL_0020: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0021: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0022: stelem.ref 

    &lt;br /&gt;IL_0023: ldloc.0&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0024: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 1 

    &lt;br /&gt;IL_0029: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_4 

    &lt;br /&gt;IL_002d: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_002e: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_002f: stelem.ref 

    &lt;br /&gt;IL_0030: ldloc.0&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0031: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_0036: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;Substring&amp;quot; 

    &lt;br /&gt;IL_003b: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 2 

    &lt;br /&gt;IL_0040: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_0045: stloc.1&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0046: ldloc.1&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0047: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_004c: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_1 

    &lt;br /&gt;IL_0050: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0051: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0052: stelem.ref 

    &lt;br /&gt;IL_0053: ldloc.1&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0054: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 1 

    &lt;br /&gt;IL_0059: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_2 

    &lt;br /&gt;IL_005d: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_005e: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_005f: stelem.ref 

    &lt;br /&gt;IL_0060: ldloc.1&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0061: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_0066: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;Replace&amp;quot; 

    &lt;br /&gt;IL_006b: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 2 

    &lt;br /&gt;IL_0070: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_0075: stloc.2&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0076: ldloc.2&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0077: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_007c: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_5 

    &lt;br /&gt;IL_0080: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0081: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0082: stelem.ref 

    &lt;br /&gt;IL_0083: ldloc.2&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0084: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 1 

    &lt;br /&gt;IL_0089: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_6 

    &lt;br /&gt;IL_008d: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_008e: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_008f: stelem.ref 

    &lt;br /&gt;IL_0090: ldloc.2&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0091: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_0096: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;PadRight&amp;quot; 

    &lt;br /&gt;IL_009b: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 2 

    &lt;br /&gt;IL_00a0: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_00a5: stloc.3&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00a6: ldloc.3&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00a7: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_00ac: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_7 

    &lt;br /&gt;IL_00b0: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00b1: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00b2: stelem.ref 

    &lt;br /&gt;IL_00b3: ldloc.3&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00b4: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 1 

    &lt;br /&gt;IL_00b9: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_8 

    &lt;br /&gt;IL_00bd: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00be: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00bf: stelem.ref 

    &lt;br /&gt;IL_00c0: ldloc.3&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00c1: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_00c6: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;ToUpper&amp;quot; 

    &lt;br /&gt;IL_00cb: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_00d0: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_00d5: stloc.s&amp;#160;&amp;#160;&amp;#160; V_4 

    &lt;br /&gt;IL_00d7: ldloc.s&amp;#160;&amp;#160;&amp;#160; V_4 

    &lt;br /&gt;IL_00d9: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_00de: ret&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Enjoy! Next time … who knows what?&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13925" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 2</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/27/to-bind-or-not-to-bind-dynamic-expression-trees-part-2.aspx</link><pubDate>Wed, 27 Aug 2008 23:05:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13917</guid><dc:creator>bart</dc:creator><slash:comments>3</slash:comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;Welcome back to the dynamic expression tree fun. Last time we designed our simplified expression tree class library we’ll be using to enable dynamic treatment of objects. Today, we’ll take this one step further by emitting IL code that resolves the operations invoked on such dynamic objects &lt;u&gt;at runtime&lt;/u&gt; through a mechanism called binders. Before we dive in, let me point out that everything discussed in this series is greatly simplified just to illustrate the core ideas and base mechanisms/principles that make dynamic language stuff work.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Introducing IL generation&lt;/h1&gt;  &lt;p&gt;Dynamic code compilation is a wonderful thing. It’s not that hard once you get the basics right (and have some level of IL opcode understanding) but quite hard to debug. Luckily we have tools like &lt;a href="http://blogs.msdn.com/haibo_luo/archive/2008/03/07/8107924.aspx"&gt;Haibo Luo’s IL Visualizer&lt;/a&gt;. Since I’ll be using this, download it, extract the ZIP file, compile the whole solution and copy ILMonitor\bin\Debug\*.dll to %programfiles%\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers. Alternatively you can put it in your personal Visual Studio 2008\Visualizers folder.&lt;/p&gt;  &lt;p&gt;So, what’s our task? Assume we have the following piece of sample code:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Program
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main(&lt;span style="color:blue;"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;o = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;o&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;call = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Call(o, &lt;span style="color:#a31515;"&gt;&amp;quot;Substring&amp;quot;&lt;/span&gt;, a, b);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;func = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(call, o, a, b);
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func);
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func.&lt;strong&gt;&lt;u&gt;Compile()&lt;/u&gt;&lt;/strong&gt;.DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 1, 2));
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;We already know how to construct the objects and to represent it as a string (which would be (o, a, b) =&amp;gt; o.Substring(a, b)). Now we need to focus on the marked Compile method on LambdaDynamicExpression. Starting with the signature of the delegate, we want to create (at runtime) a method that takes in three “dynamic” parameters (corresponding to parameter expressions o, a and b), returning a resulting object. Since we don’t have any type information available, everything should be System.Object, so we’d end up with the following delegate:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font color="#0000ff"&gt;delegate object &lt;/font&gt;&lt;font color="#008080"&gt;TheDynamicLambdaFunction&lt;/font&gt;(&lt;font color="#0000ff"&gt;object &lt;/font&gt;o, &lt;font color="#0000ff"&gt;object &lt;/font&gt;a, &lt;font color="#0000ff"&gt;object &lt;/font&gt;b);&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Looking at Compile as a black box, it will return an instance of this delegate pointing at an on-the-fly generated method corresponding to the lambda’s body expression. Returning a System.Delegate, one can call DynamicInvoke (or cast it to a compatible delegate) to invoke it with the given parameters. Obviously we want the call to do “the right thing”, in the sample above it would correspond to a method call to System.String::Substring on “Bart”, passing in startIndex 1 and length 2, producing another string containing “ar”.&lt;/p&gt;

&lt;p&gt;It should be clear that we need to emit IL on the fly to translate the lambda expression but also the lambda’s body which could be anything, not just a MethodCallDynamicExpression. Since we lack other expression node types, one such (trivial) thing would be:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;x = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;I = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(&lt;strong&gt;&lt;u&gt;x&lt;/u&gt;&lt;/strong&gt;, x);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;which is just the identity function (the underlined bold ‘o’ above indicates the lamdba’s body). I intentionally named the expression above “I” conform SKI combinators where I is defined as λx . x. Similarly we could define the K combinator as:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;x = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;y = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;y&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;K = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(x, x, y);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(K);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(K.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 123));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;but we got sidetracked, so time to move on. The whole point here is that we can’t assume the body of the lambda to be a MethodCallDynamicExpression. So, how do we tackle this? An important observation one can make is this: an expression represents a single value. Right, so what? Wait a minute, is IL-code not stack-based? Adding the two things together we could think of the following solution:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Calling a Compile method on an expression tree object, given a writeable stream for IL instructions, should add all the instructions to the stream required to evaluate the expression, leaving the result of the evaluation on top of the stack.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A LambdaDynamicExpression is the only dynamic expression that supports a publicly visible Compile method. It’s pseudo-code would look like:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Create an IL stream; here the IL stack is empty.&lt;/li&gt;

  &lt;li&gt;Take the Body expression and compile it by emitting IL instructions for it; this causes the IL stack to be one high.&lt;/li&gt;

  &lt;li&gt;Add an IL return instruction to return the object on top of the stack.&lt;/li&gt;

  &lt;li&gt;Return a delegate pointing to the method represented by the generated IL code.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Supporting expression compilation&lt;/h1&gt;

&lt;p&gt;To make this work, we’ll first extend the base class by adding one more method:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Class representing a dynamic expression tree.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Appends IL instructions to calculate the expression&amp;#39;s runtime value, putting it on top of the evaluation stack.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;ilgen&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;IL generator to append to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&amp;quot;ldArgs&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Lambda argument mappings.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;protected internal abstract void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs);&lt;/pre&gt;

  &lt;pre class="code"&gt;    …&lt;br /&gt;}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This method will take in two things: the IL generator (referred to as “IL stream” in the previous paragraph) and a mapping table for the lambda’s parameter expressions. Why do we need the latter, or better: what does it map the parameter expressions to? Assume we’re compiling&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(o, a, b) =&amp;gt; o.Substring(a, b)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;While traversing the expression tree, asking every node in the correct order to emit IL instructions, we’ll encounter references to the parameters again. Our goal is to write a dynamic method looking like this:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font color="#0000ff"&gt;object &lt;/font&gt;GeneratedDynamicMethod(&lt;font color="#0000ff"&gt;object &lt;/font&gt;o, &lt;font color="#0000ff"&gt;object &lt;/font&gt;a, &lt;font color="#0000ff"&gt;object &lt;/font&gt;b)

    &lt;br /&gt;{

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;o.Substring(a, b);

    &lt;br /&gt;}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;where the . obviously denotes a dynamic method call in this case. As we encounter parameter expressions like o, a or b during the translation for the method body, we need to know how to load those parameters from the argument list on the dynamic method. First of all, notice the lambda parameters got mapped in order of specification to correspond to arguments on the generated dynamic method, i.e. o as the first lambda parameter and is the first parameter on the generated method. And so on. This is precisely what the ldArgs argument on Compile stands for: a mapping from the parameter expression representation from the lambda parameters onto the concrete indices for the arguments:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;o –&amp;gt; 0
    &lt;br /&gt;a –&amp;gt; 1

    &lt;br /&gt;b –&amp;gt; 2&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Whenever we encounter such a parameter expression during the compilation, we know the position of the argument, so we can emit a &lt;em&gt;ldarg&lt;/em&gt; instruction. This is the most trivial Compile override:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!ldArgs.ContainsKey(&lt;span style="color:blue;"&gt;this&lt;/span&gt;))
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Parameter expression &amp;quot; &lt;/span&gt;+ Name + &lt;span style="color:#a31515;"&gt;&amp;quot; is not in scope.&amp;quot;&lt;/span&gt;);

        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg, ldArgs[&lt;span style="color:blue;"&gt;this&lt;/span&gt;]);
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    …
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This simply says, whenever code needs to be emitted for a ParameterDynamicExpression, simply try to find it in the dictionary to map it onto the formal parameter index on the dynamic method being emitted and turn it into a &lt;em&gt;ldarg &lt;/em&gt;instruction for that argument index. Real full-fledged expression tree implementations would be slightly more complicated because arguments could be hidden when dealing with nested lambdas (quoting, invocation expressions, etc) but that would take us too far away from home.&lt;/p&gt;

&lt;p&gt;For the LambdaDynamicExpression, besides a public Compile method, there will also be an override to the inherited one. It simply asks the Body expression to emit itself (which will result in a one-level high stack containing the evaluation result of the body expression), followed by a ret instruction (simply returning the value evaluated through the Body’s IL code preceding it):&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
    {
        Body.Compile(ilgen, ldArgs);
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ret);
    }&lt;/pre&gt;

&lt;pre class="code"&gt;    …&lt;br /&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Emitting code&lt;/h1&gt;

&lt;p&gt;For this post, we’ll omit an implementation for MethodCallDynamicExpression as that will be part of the next post focusing on binders. All we want to get to work today is the I combinator or identity function (yeah, another world-beater :-)):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;x = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;I = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(x, x);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;));&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;In other words, today we’ll focus on the plumbing of emitting the code and wrapping the method in a delegate that can be returned upon calling LambdaDynamicExpression.Compile. The result for the sample above would be equivalent to:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Delegate &lt;/span&gt;Compile()
{
    &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;, &lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt;(&lt;u&gt;&lt;span style="color:blue;"&gt;delegate&lt;/span&gt;(&lt;span style="color:blue;"&gt;object &lt;/span&gt;x) { &lt;span style="color:blue;"&gt;return &lt;/span&gt;x; }&lt;/u&gt;);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The underlined portion is the code corresponding to I’s compilation. In IL-terms it would be as simplistic as this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;ldarg.0
    &lt;br /&gt;ret&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This emitted IL method body then needs to get the signature that says “taking in an object, returning an object”. All of this makes up the &lt;em&gt;dynamic method&lt;/em&gt;. But we’re not done yet, as we need to return a delegate to it. In the free translation above, I’ve leveraged the generic System.Func&amp;lt;T1,R&amp;gt; delegate but we only have a limited number of those (up to four arguments), so what if we encounter a method that takes more arguments? Indeed, we’ll need to generate our own delegate types as well. Notice we could cache those very efficiently: the ones with arity (~ number of parameters) up to 4 could simply be mapped onto System.Func delegates with System.Object type parameters, while others would be generated on the fly and kept for reuse if another method with same arity gets compiled. We’ll omit this optimization for now.&lt;/p&gt;

&lt;p&gt;Here’s how the code to create our own delegate type looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;GetDynamicDelegate(&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] argumentTypes, &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;returnType)
{
    &lt;span style="color:green;"&gt;//
    // Assemblies contain modules; generate those with unique names.
    // The generated assembly is runtime only (doesn&amp;#39;t need to be saved to disk).
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AssemblyBuilder &lt;/span&gt;assemblyBuilder = &lt;span style="color:#2b91af;"&gt;AppDomain&lt;/span&gt;.CurrentDomain.DefineDynamicAssembly(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AssemblyName&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Guid&lt;/span&gt;.NewGuid().ToString()), &lt;span style="color:#2b91af;"&gt;AssemblyBuilderAccess&lt;/span&gt;.Run);
    &lt;span style="color:#2b91af;"&gt;ModuleBuilder &lt;/span&gt;moduleBuilder = assemblyBuilder.DefineDynamicModule(&lt;span style="color:#2b91af;"&gt;Guid&lt;/span&gt;.NewGuid().ToString());

    &lt;span style="color:green;"&gt;//
    // Our delegate is a private sealed type deriving from MultiCastDelegate.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder = moduleBuilder.DefineType(&lt;span style="color:#a31515;"&gt;&amp;quot;Lambdas&amp;quot;&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.NotPublic | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.Sealed | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.AutoLayout | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.AnsiClass, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;MulticastDelegate&lt;/span&gt;));

    &lt;span style="color:green;"&gt;//
    // The delegate&amp;#39;s constructor is a &amp;quot;special name&amp;quot; method with signature (object native int).
    // It doesn&amp;#39;t have a method body by itself; rather, it&amp;#39;s supplied by the managed runtime.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ConstructorBuilder &lt;/span&gt;ctorBuilder = typeBuilder.DefineConstructor(&lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Public | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.HideBySig | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.SpecialName | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.RTSpecialName, &lt;span style="color:#2b91af;"&gt;CallingConventions&lt;/span&gt;.Standard, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] { &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;), &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;IntPtr&lt;/span&gt;) });
    ctorBuilder.SetImplementationFlags(&lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Runtime | &lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Managed);

    &lt;span style="color:green;"&gt;//
    // We only need the Invoke method (BeginInvoke and EndInvoke are irrelevant for us).
    // It doesn&amp;#39;t have a method body by itself; rather, it&amp;#39;s supplied by the managed runtime.
    // Here our delegate signature is enforced.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodBuilder &lt;/span&gt;invokeMethodBuilder = typeBuilder.DefineMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Invoke&amp;quot;&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Public | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.NewSlot | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.HideBySig | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Virtual, &lt;span style="color:#2b91af;"&gt;CallingConventions&lt;/span&gt;.HasThis, returnType, argumentTypes);
    invokeMethodBuilder.SetImplementationFlags(&lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Runtime | &lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Managed);

    &lt;span style="color:green;"&gt;//
    // Return the created delegate type.
    // Notice we could cache this for reuse by other dynamic methods.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;typeBuilder.CreateType();
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Lots of attribute flags which you can read all about in the CLI specification. I don’t pretend to memorize all of those attributes; why would I if ILDASM makes life just great? :-)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="260" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb.png" width="631" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is the screenshot of ILDASM showing a delegate for a method with signature object(object, object) as you can see on the Invoke method. We don’t need any of the asynchronous pattern implementation, so we just need a constructor and Invoke method (see section IIA.13.6 on “Delegates” in the CLI standard). One special thing about those is they don’t have an IL code body as they are “runtime managed” (see IIA.14.4.3 on “Implementation Attributes of Methods” in the CLI standard):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_3.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="166" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_3.png" width="640" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now that we can generate the delegate, we just need to ask the lambda (since that’s the root) expression tree to emit its IL code, which will traverse the entire tree. In order to be able to do this, we need to keep mapping information about the lambda parameters mapped onto the formal arguments as mentioned earlier. Here’s the result:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Delegate &lt;/span&gt;Compile()
{
    &lt;span style="color:green;"&gt;//
    // Map the lambda parameters onto formal argument indices.
    // Also build up the argument type array.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;args = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[Parameters.Count];
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;ldArgs = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;();
    &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; args.Length; i++)
    {
        args[i] = &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;);
        ldArgs[Parameters[i]] = i;
    }

    &lt;span style="color:green;"&gt;//
    // Compile the expression tree to an IL method body.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;method = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicMethod&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;&amp;quot;&lt;/span&gt;, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;), args);
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;ilgen = method.GetILGenerator();
    Compile(ilgen, ldArgs);

    &lt;span style="color:green;"&gt;//
    // Get the delegate matching the dynamic method signature.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;dynamicDelegate = GetDynamicDelegate(args, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;));

    &lt;span style="color:green;"&gt;//
    // Return a delegate pointing at our dynamic method.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;method.CreateDelegate(dynamicDelegate);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This code should be relatively straightforward. First we create the mapping while building up an array just containing typeof(object)’s (since all arguments are objects in our dynamic world). Next we create a dynamic method with the right signature, produce the IL generator and let the expression compilation do all of the work to emit the IL. And finally we stick the whole thing in a dynamically created delegate that matches the signature, returning that to the caller. Setting a breakpoint on the last line and executing for the “I” identity combinator shows this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_4.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="184" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_4.png" width="560" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is the IL visualizer we installed earlier. Notice the friendly string representation for the dynamic method shows the signature, which matches the one of the dynamic lambda in the watch window (which is just “I”). Bringing up the IL visualizer shows stunningly complex code:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_5.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="133" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_5.png" width="305" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ignore the NOPs inserted by the IL generator, but IL_0000 was emitted by ParameterDynamicExpression.Compile through the compilation of the lambda body. IL_0006 was emitted subsequently by LambdaDynamicExpression.Compile and the stack is nicely in balance. Sure enough, the result printed is:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_6.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="119" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_6.png" width="372" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Woohoo – truly dynamic (though simplistic) execution! Next time: method call expressions and binders.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13917" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 1</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-1.aspx</link><pubDate>Wed, 27 Aug 2008 05:40:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13913</guid><dc:creator>bart</dc:creator><slash:comments>4</slash:comments><description>&lt;p&gt;In the previous post, I outlined the use of the expression trees from the System.Linq.Expressions namespace. Let’s recap to set the scene:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt;&amp;gt; data = (&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt; &lt;/font&gt;s, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt; &lt;/font&gt;a, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt; &lt;/font&gt;b) =&amp;gt; s.Substring(a, b);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;produces (deep breadth)&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;)&lt;/u&gt;, &lt;font color="#800000"&gt;“s”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;)&lt;/u&gt;, &lt;font color="#800000"&gt;“a”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;)&lt;/u&gt;, &lt;font color="#800000"&gt;“b”&lt;/font&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt;&amp;gt; data = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt;&amp;gt;(       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;)&lt;/u&gt;.GetMethod(&lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, &lt;u&gt;&lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Type&lt;/font&gt;[] { &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;), &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;) }&lt;/u&gt;), a, b),         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b         &lt;br /&gt;);         &lt;br /&gt;        &lt;br /&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt; fun = data.Compile();         &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fun(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, 1, 2));&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where I’ve indicated all the strong typing using underlines. Wow, that’s a lot dude! Based on all of this strong typing, there are little or no runtime surprises possible concerning running the right method (unless a MissingMethodException occurs for some reason). Obviously, expression trees could be much more complex but to illustrate the core points of the type system, we’ll restrict ourselves to parameters, method calls and lambdas.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;So what do we want to try now? We want to design an API similar to the one used above but without all this type information. Essentially, it would look like:&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“s”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“a”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“b”&lt;/font&gt;);     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008080"&gt;LambdaExpression&lt;/font&gt; data = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, a, b),       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b       &lt;br /&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Delegate&lt;/font&gt; fun = data.Compile();       &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fun.&lt;u&gt;&lt;strong&gt;Dynamic&lt;/strong&gt;Invoke&lt;/u&gt;(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, 1, 2));&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;and all of a sudden we see the dynamic aspect lurking around the corner on the very last line where we call through the weakly-typed delegate passing in three &lt;em&gt;objects&lt;/em&gt; which just happen to be a string and two ints, causing the lookup for a Substring method applied to s (becoming “Bart”) with arguments a and b (respectively 1 and 2) to succeed. The important thing here though is that a “Substring” method with a compatible signature might be available on another type, maybe type Bar, but taking in two longs:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Foo &lt;/font&gt;Substring(&lt;font color="#0000ff"&gt;long &lt;/font&gt;a, &lt;font color="#0000ff"&gt;long &lt;/font&gt;b) { … }       &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The calling code would still work and the console would print the result of Foo.ToString on the instance returned by Bar.Substring. What it takes to make this work consists of three things:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Dynamic expression trees (i.e. as the one above with stripped type information); &lt;/li&gt;    &lt;li&gt;IL code generation at runtime on the fly (to produce the delegate “fun” in the sample above) &lt;/li&gt;    &lt;li&gt;Binders (things that provide runtime support to resolve method calls) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Of course you could go much further than this with complete ASTs (the big brothers to expression trees) and “rules” but we’re not going to reinvent the DLR :-). &lt;a href="http://blogs.msdn.com/mmaly"&gt;Martin Maly&lt;/a&gt; has quite some information on those topics on his blog (must-reads!). Today we’ll cover the first bullet point.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Our dynamic expression trees&lt;/h1&gt;  &lt;p&gt;To disambiguate with the LINQ expression trees, let’s sneak the word Dynamic in, making our sample look like:&lt;/p&gt;  &lt;blockquote&gt;&lt;font color="#008080"&gt;ParameterDynamicExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“s”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterDynamicExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“a”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterDynamicExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“b”&lt;/font&gt;);     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008080"&gt;LambdaDynamicExpression&lt;/font&gt; data = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Lambda(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, a, b),       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b       &lt;br /&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Delegate&lt;/font&gt; fun = data.Compile();       &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fun.&lt;u&gt;&lt;strong&gt;Dynamic&lt;/strong&gt;Invoke&lt;/u&gt;(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, 1, 2));&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;All of those *DynamicExpression classes extend the DynamicExpression base class while having a factory method on DynamicExpression too, following the design of LINQ’s expression trees. We’ll omit the NodeType property for simplicity and the Type property, because we obviously don’t want a static type to be associated with each expression tree node. We’ll also get rid of a lot of node types, just leaving the factories in for our three node types:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_E57/image.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="369" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_E57/image_thumb.png" width="595" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So, how does this look like? The factory methods will be just convenient syntax around internal constructor calls producing the concrete node types. In addition, we’ll override ToString to produce a friendly-on-the-eye string representation of expression trees, much like our static LINQ friends. First, the DynamicExpression base class:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression &lt;/span&gt;Parameter(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;(name);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallDynamicExpression &lt;/span&gt;Call(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;instance, &lt;span style="color:blue;"&gt;string &lt;/span&gt;method, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;[] arguments)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallDynamicExpression&lt;/span&gt;(instance, method, arguments);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression &lt;/span&gt;Lambda(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;body, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;[] parameters)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression&lt;/span&gt;(body, parameters);
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;&lt;font color="#808080"&gt;    &lt;/font&gt;protected internal abstract void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb);

&lt;span style="color:blue;"&gt;&lt;font color="#808080"&gt;&lt;/font&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;&lt;font color="#808080"&gt;&lt;/font&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;    public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StringBuilder&lt;/span&gt;();
        ToString(sb);
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;sb.ToString();
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;We’ll extend this class a bit more in the next part where we’ll tackle compilation, but let’s move on to each of the three subtypes right now:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;ParameterDynamicExpression(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
    {
        Name = name;
    }

    &lt;span style="color:blue;"&gt;public string &lt;/span&gt;Name { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

&lt;span style="color:blue;"&gt;    protected internal override void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb)
    {
        sb.Append(Name);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Nothing surprising here. The expression for a dynamic method call is a slightly bit more complicated :-)…&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;MethodCallDynamicExpression(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;instance, &lt;span style="color:blue;"&gt;string &lt;/span&gt;method, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;[] arguments)
    {
        Object = instance;
        Method = method;
        Arguments = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;&amp;gt;(arguments);
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;&amp;gt; Arguments { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;Object { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public string &lt;/span&gt;Method { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }&lt;/pre&gt;

  &lt;pre class="code"&gt;    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb)
    {
        Object.ToString(sb);
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;);
        sb.Append(Method);
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;(&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;int &lt;/span&gt;n = Arguments.Count;
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; n; i++)
        {
            Arguments[i].ToString(sb);
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(i != n - 1)
                sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
        }

        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;)&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;I told’ya it was going to be mind-blowing. The core thing to notice though is the composability because of the use of DynamicExpressions as the Object (i.e. the instance where we’ll invoke the method on) and the Arguments collection members. Also notice we don’t support static method calls in here (for which Object would be null – you can envision the right checking in the factory method, omitted for brevity) although it would be perfectly possible to come up with such a thing (think about “global functions” for example, but remember we don’t have a type that tells us where to look for the method – ideally you’d have a mixture of statically and dynamically typed trees interwoven). Oh, and the pretty printing logic in ToString isn’t too complex either…&lt;/p&gt;

&lt;p&gt;Finally, let’s move on to the lambda expression class:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;LambdaDynamicExpression(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;body, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;[] parameters)
    {
        Body = body;
        Parameters = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;&amp;gt;(parameters);
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;Body { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;&amp;gt; Parameters { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Delegate &lt;/span&gt;Compile()
    {
        &lt;span style="color:blue;"&gt;return null&lt;/span&gt;;
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb)
    {
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;(&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;int &lt;/span&gt;n = Parameters.Count;
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; n; i++)
        {
            Parameters[i].ToString(sb);
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(i != n - 1)
                sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
        }

        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;) =&amp;gt; &amp;quot;&lt;/span&gt;);
        Body.ToString(sb);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Same deal concerning parameterization based on DynamicExpression instances. I promise you the Compile method will be pretty interesting to say the least, so stay tuned for the next post!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13913" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 0</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-0.aspx</link><pubDate>Tue, 26 Aug 2008 07:59:04 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13912</guid><dc:creator>bart</dc:creator><slash:comments>3</slash:comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;By now, most of my blog readers will be familiar with the simple concept of expression trees in C# 3.0 and VB 9.0. A quick recap. What’s the type of the expression below?&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s, &lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &lt;/font&gt;b) =&amp;gt; s.Substring(a, b)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Shockingly, you can’t tell. Why? Lambdas have two forms of representation: code (as anonymous methods) or data (as expression trees). One more time:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt; code = (&lt;font color="#0000ff"&gt;string &lt;/font&gt;s, &lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &lt;/font&gt;b) =&amp;gt; s.Substring(a, b);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;produces&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt; code = &lt;font color="#0000ff"&gt;delegate &lt;/font&gt;(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s, &lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &lt;/font&gt;b) { &lt;font color="#0000ff"&gt;return &lt;/font&gt;s.Substring(a, b); };&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt;&amp;gt; data = (&lt;font color="#0000ff"&gt;string &lt;/font&gt;s, &lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &lt;/font&gt;b) =&amp;gt; s.Substring(a, b);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;produces (deep breadth)&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;), &lt;font color="#800000"&gt;“s”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;), &lt;font color="#800000"&gt;“a”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&g