Getting started

edit

Install the package

dotnet package add Meziantou.Framework.CodeDom

The 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();

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