Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think the key points about CodeDOM and Reflection.Emit are following:</p> <ul> <li><p><strong>CodeDom</strong> generates C# source code and is usually used when generating code to be included as part of a solution and compiled in the IDE (for example, LINQ to SQL classes, WSDL, XSD all work this way). In this scenario you can also use partial classes to customize the generated code. It is less efficient, because it generates C# source and then runs the compiler to parse it (again!) and compile it. You can generate code using relatively high-level constructs (similar to C# expressions &amp; statements) such as loops.</p></li> <li><p><strong>Reflection.Emit</strong> generates an IL so it directly produces an assembly that can be also stored only in memory. As a result is a lot more efficient.You have to generate low-level IL code (values are stored on stack; looping has to be implemented using jumps), so generating any more complicated logic is a bit difficult.</p></li> </ul> <p>In general, I think that Reflection.Emit is usually considered as the preferred way to generate code at runtime, while CodeDOM is preferred when generating code before compile-time. In your scenario, both of them would probably work fine (though CodeDOM may need higher-privileges, because it actually needs to invoke C# compiler, which is a part of any .NET installation).</p> <p>Another option would be to use the <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression(VS.100).aspx" rel="noreferrer"><code>Expression</code> class</a>. In .NET 4.0 it allows you to generate code equivalent to C# expressions and statements. However, it doesn't allow you to generate a classes. So, you may be able to combine this with Reflection.Emit (to generate classes that delegate implementation to code generated using <code>Expression</code>). For some scenarios you also may not really need a full class hierarchy - often a dictionary of dynamically generated delegates such as <code>Dictionary&lt;string, Action&gt;</code> could be good enough (but of course, it depends on your exact scenario).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload