You might be able to kill two bird with one stone with Roslyn (aka ".NET Compiler Platform"). You'll need the package Microsoft.CodeAnalysis.CSharp
.
First, you can use the SyntaxFactory
class to generate syntax nodes, which you can combine into larger structures (members, methods, classes, namespaces, compilation units).
You can also get a nicely formatted representation of your syntax nodes with ToString()
or ToFullString()
(with correct indentation and line breaks and everything), which is what you were originally looking for.
There are quite a few tutorials online on how to use this API (like 1, 2), and there's the Roslyn Quoter website that can convert a piece of C# code into SyntaxFactory
calls.
Second, you can then use the resulting CSharpSyntaxNode
to create a CSharpSyntaxTree
, which you can compile into IL with the help of CSharpCompilation
(after all, Roslyn is the reference C# compiler).
If you want, you can even emit the generates assembly into a stream, get the assembly's binary data from there, and load your newly created assembly into your currently executing assembly, and dynamically instantiate the types you just defined.