CsCompile

About this project
Sample of dynamic C# code compilation and invoke.
Languages
Wiki / Home

Overview

The solution contains two projects that demonstrate how to dynamically compile C# code at runtime and invoke a method in the generated Assembly.

Dynamic code compilation is a reasonably advanced technique that can be used by developers to implement runtime flexibility and scripting features in their applications.

CsCompileFramework

Targets the .NET Framework and uses the CSharpCodeProvider class as described in the Microsoft Learn article Compile code programmatically by using C# compiler .

CsCompileCore

Targets .NET Core and uses modern classes that encapsulate Rosyln compiler functionality. There are many code samples available online that use subtly different coding patterns. The sample code is an attempt to strip the required code down to the minimum. See the other samples for hints on how to incorporate more advanced features.

😠 NOTE — Getting this .NET Core sample working was quite taxing. The dynamic compile failed with warnings like Predefined type 'System.Object' is not defined or imported, which suggested that the references passed to the compiler were incorrect. It took hours of research and experiments to determine the correct references to add. Look at the MetadataReference array in Program.cs to see the correct minimum required references.


Both projects load source code from the file Worker.cs at runtime, compile it and emit the generated Assembly into a memory stream. An Assembly instance is then created from the stream, the Worker class is instantiated and one of its methods is dynamically invoked.

The follow screenshot shows the output from the dynamically compiled Worker class method that generates some cryptographically secure random bits.

screenshot

Orthogonal Programming Link

Project stats