Is it possible to dynamically compile and execute C# code fragments?
The best solution in C#/all static .NET languages is to use the CodeDOM for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)
Here's a nice short example take from LukeH's blog, which uses some LINQ too just for fun.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
static void Main(string[] args)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Range(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
The class of primary importance here is the CSharpCodeProvider
which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.
Here is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the System.Reflection
namespace.
Is it possible to compile and execute new code at runtime in .NET?
Yes! Using methods found in the Microsoft.CSharp, System.CodeDom.Compiler, and System.Reflection name spaces. Here is a simple console app that compiles a class ("SomeClass") with one method ("Add42") and then allows you to invoke that method. This is a bare-bones example that I formatted down to prevent scroll bars from appearing in the code display. It is just to demonstrate compiling and using new code at run time.
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
namespace RuntimeCompilationTest {
class Program
{
static void Main(string[] args) {
string sourceCode = @"
public class SomeClass {
public int Add42 (int parameter) {
return parameter += 42;
}
}";
var compParms = new CompilerParameters{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults =
csProvider.CompileAssemblyFromSource(compParms, sourceCode);
object typeInstance =
compilerResults.CompiledAssembly.CreateInstance("SomeClass");
MethodInfo mi = typeInstance.GetType().GetMethod("Add42");
int methodOutput =
(int)mi.Invoke(typeInstance, new object[] { 1 });
Console.WriteLine(methodOutput);
Console.ReadLine();
}
}
}
C# How to add a code to execute at Runtime
Searched for 'dynamic c# code execution' and Google came up with this blog from 2002... This might work for you..
http://www.west-wind.com/presentations/dynamiccode/dynamiccode.htm
The article refers to System.CodeDom.Compiler to compile a assembly on the fly and then using Reflection to execute that code. Sounds like fun ;)
EDIT: As DaveL suggested: Is it possible to dynamically compile and execute C# code fragments?
Dynamically compile multiple files into assembly using Rosyln
Nick Polyak has written a complete article on Code Project: Using Roslyn for Compiling Code into Separate Net Modules and Assembling them into a Dynamic Library and with complete source code available on GitHub.
While this might not be exactly what you are looking for, it should help you getting started with Roslyn concepts, how to create a CSharpCompilation
from a SyntaxTree
and emit it to a Stream
.
Is it possible to create/execute code in run-time in C#?
Absolutely - that's exactly what I do for Snippy for example, for C# in Depth. You can download the source code here - it uses CSharpCodeProvider
.
There's also the possibility of building expression trees and then compiling them into delegates, using DynamicMethod
, or the DLR in .NET 4... all kinds of things.
Related Topics
What Is a Nullreferenceexception, and How to Fix It
What Is an Indexoutofrangeexception/Argumentouto
frangeexception and How to Fix It
When Correctly Use Task.Run and When Just Async-Await
Select Tag Helper in ASP.NET Core MVC
How to Enable Cors in ASP.NET Core
How to Read a CSV File into a .Net Datatable
Addtransient, Addscoped and Addsingleton Services Differences
How to Get the Index of the Current Iteration of a Foreach Loop
Copy the Entire Contents of a Directory in C#
C# Lambda Expressions: Why Should I Use Them
Transactionscope Automatically Escalating to Msdtc on Some Machines
Programmatic Equivalent of Default(Type)
Why Is Thread.Sleep So Harmful
Passing Strings from C# to C++ Dll and Back - Minimal Example
Using a Class Defined in a C++ Dll in C# Code
Is Is Possible to Export Functions from a C# Dll Like in VS C++