Getting started
editInstall the package
dotnet package add Meziantou.Framework.CodeDomThe types are in the Meziantou.Framework.CodeDom namespace. The examples of this documentation omit the using directives, and check their results with assertions such as Assert.Equal.
Build a file
A file is a CompilationUnit. Add using directives and namespaces to it, types to the namespaces, members to the types, and statements to the members. The Add* extension methods attach an object to its parent and return it, so you can keep building on it:
var unit = new CompilationUnit();
unit.AddUsing("System");
var ns = unit.AddNamespace("Demo");
var type = ns.AddType(new ClassDeclaration("Greeter")
{
Modifiers = Modifiers.Public,
});
var method = type.AddMember(new MethodDeclaration("GetMessage")
{
Modifiers = Modifiers.Public | Modifiers.Static,
ReturnType = typeof(string),
});
var nameArgument = method.AddArgument("name", typeof(string));
method.Statements = new ReturnStatement(Expression.Add("Hello ", nameArgument, "!"));
var generatedCode = unit.ToCsharpString();- AddUsing, AddNamespace, AddType, AddMember and AddArgument create and attach the declarations.
ReturnType = typeof(string)converts theTypeto a TypeReference.- Expression.Add builds
"Hello " + name + "!". The string literals convert to LiteralExpression, and the argument declaration to a reference to the argument. - Statements accepts a single statement, which converts to a collection.
Write the code
ToCsharpString() writes any code object, from a whole compilation unit to a single expression:
using System;
namespace Demo
{
public class Greeter
{
public static string GetMessage(string name)
{
return (("Hello " + name) + "!");
}
}
}To write to a file or a stream, use CSharpCodeGenerator: it writes to a TextWriter, with \n line endings and four spaces of indentation. See Writing code.
Next steps
- Declarations: every kind of type and member.
- Statements and expressions: conditions, loops, method calls, object creation...