/CodeBuilder

Extensible framework for generating code

Primary LanguageC#Apache License 2.0Apache-2.0

CodeBuilder

NCodeBuilder is a fluent .NET framework for code generation. It is similar to a StringBuilder, but with support for code generation concepts such as indentation, code blocks, comments, etc.

Getting started

NCodeBuilder is available as a NuGet package named NCodeBuilder. It supports netstandard2.0 and net461 targets.

To install the NuGet package:

# From Package Manager
Install-Package NCodeBuilder -Version 0.1.0
# From the dotnet CLI
dotnet add package NCodeBuilder --version 0.1.0

Example

// Use the NCodeBuilder.CodeBuilder class to build the code you require.
var builder = new CodeBuilder(LanguageProvider.CSharp())
    .Comment("<auto-generated/>")
    .Blank
    .Using("System")
    .Using("System.Collection.Generics")
    .UsingStatic("System.Console")
    .Blank
    .Namespace("MyApp")
        .Block("public class Program")
            .Block("static void Main(string[] args)")
                .Line(@"WriteLine(""Hello World"");")
            .EndBlock()
        .EndBlock()
    .EndNamespace();
    
// Generate the code
string code = builder.ToString();

The above code generates the following:

// <auto-generated/>

using System;
using System.Collection.Generics;
using static System.Console;

namespace MyApp
{
    public class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Hello World");
        }
    }
}

Additional documentation

Alternate frameworks and tools

If NCodeBuilder does not meet your needs, try one of these frameworks:

  • CodeBuilder (nuget): More strongly-typed, targetted at C# code generation only.
  • CodeWriter (nuget): Similar design to NCodeBuilder. Offers a concise mode. This is a .NET Framework library. A netstandard port can be found here (nuget).

Another option is to use Roslyn (using the Microsoft.CodeAnalysis.CSharp.SyntaxFactory class), although it can get quite verbose. Try the RoslynQuoter site to play with this.