Skip to content

fengb3/EasyCodeBuilder

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

51 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Easy Code Builder

NuGet Version License: MIT CI NuGet

A powerful and flexible library for dynamic C# code generation using a configuration-based API.

✨ Features

  • βš™οΈ Configuration-Based API: Use option objects to configure code structures
  • πŸ—οΈ Type-Safe Builder: Strongly typed options for C# code generation
  • πŸ”§ Flexible Configuration: Declarative approach with extension methods
  • πŸ“š Rich Code Constructs: Namespaces, classes, methods, properties, control structures, and more
  • ⚑ High Performance: Optimized string building with efficient rendering
  • πŸ›‘οΈ Type Safety: Compile-time safety with strongly typed options
  • πŸ“– XML Documentation: Complete IntelliSense support

πŸš€ Quick Start

Installation

dotnet add package Fengb3.EasyCodeBuilder

Basic Usage

API Calling:

using Fengb3.EasyCodeBuilder.Csharp;
using static Fengb3.EasyCodeBuilder.Csharp.Code;

var code = Create()
    .Using("System")
    .Namespace(ns => {
        ns.Name = "MyProject";
        ns.Public.Class(cls => {
            cls.WithName("Person");
            cls.Public.AutoProperty(p => p
                .WithType("string")
                .WithName("Name")
            );
            cls.Public.AutoProperty(p => p
                .WithType("int")
                .WithName("Age")
            );
        });
    })
    .Build();

Generated Code:

using System;

namespace MyProject
{
  public class Person
  {
    public string Name { get; set; }
    public int Age { get; set; }
  }
}

πŸ“š Documentation

For detailed documentation and examples, see this README and the test project examples in the repository.

πŸ—οΈ Architecture

EasyCodeBuilder v0.1.0 uses a configuration-based approach with option objects:

Component Description
CodeOption Base class for all code options
Code.Create() Entry point for creating code
NamespaceOption Configure namespaces
TypeOption Configure classes, structs, interfaces
MethodOption Configure methods
AutoPropertyOption Configure auto-properties
IfOption/ElseIfOption/ElseOption Configure conditional statements
ForOption/WhileOption/ForeachOption Configure loops
SwitchOption Configure switch statements

πŸ“Š Examples

Generate a Class with Methods

API Calling:

using static Fengb3.EasyCodeBuilder.Csharp.Code;

var code = Create()
    .Using("System")
    .Namespace(ns => {
        ns.Name = "MyApp";
        ns.Public.Class(cls => {
            cls.WithName("Calculator");
            cls.Public.Method(method => {
                method.WithName("Add")
                      .WithReturnType("int")
                      .WithParameters("int a", "int b")
                      .AppendLine("return a + b;");
            });
        });
    })
    .Build();

Generated Code:

using System;

namespace MyApp
{
  public class Calculator
  {
    public int Add(int a, int b)
    {
      return a + b;
    }
  }
}

Using Keyword Configurator

The new KeywordOptionConfigurator API provides a fluent way to specify access modifiers and other keywords. Note: You need to import Fengb3.EasyCodeBuilder.Csharp.OptionConfigurations to use these extension methods.

API Calling:

using Fengb3.EasyCodeBuilder.Csharp;
using Fengb3.EasyCodeBuilder.Csharp.OptionConfigurations;

var @namespace = new NamespaceOption()
    .WithName("MyNamespace")
    .Public.Class(cls => {
        cls.WithName("MyClass");
    });

var code = @namespace.Build();

Generated Code:

namespace MyNamespace
{
  public class MyClass
  {
  }
}

You can also use the keyword configurator with auto-properties:

API Calling:

using Fengb3.EasyCodeBuilder.Csharp;
using static Fengb3.EasyCodeBuilder.Csharp.Code;

var @class = Create()
    .Class(cls => cls
        .WithName("MyClass")
        .Public.AutoProperty(prop => prop
            .WithName("MyProperty")
            .WithType(typeof(int).FullName ?? "int")
        )
    );

var classCode = @class.Build();

Generated Code:

class MyClass
{
  public System.Int32 MyProperty { get; set; }
}

Using Constructors

API Calling:

using Fengb3.EasyCodeBuilder.Csharp;
using Fengb3.EasyCodeBuilder.Csharp.OptionConfigurations;

// Create a public class using KeywordConfigurator approach
var classOption = new TypeOption()
    .WithTypeKind(TypeOption.Type.Class)
    .WithName("Person")
    .WithKeyword("public");  // TypeOption's public keyword

// Add constructor (note: Constructor doesn't support KeywordConfigurator yet)
classOption.Constructor(ctor => {
    ctor.WithKeyword("public")
        .WithParameter("string name")
        .WithParameter("int age")
        .AppendLine("Name = name;")
        .AppendLine("Age = age;");
});

// Use KeywordConfigurator for properties
classOption.Public.AutoProperty(p => p
    .WithType("string")
    .WithName("Name"));

classOption.Public.AutoProperty(p => p
    .WithType("int")
    .WithName("Age"));

var code = classOption.Build();

Generated Code:

public class Person
{
  public Person(string name, int age)
  {
    Name = name;
    Age = age;
  }
  public string Name { get; set; }
  public int Age { get; set; }
}

Control Structures - For Loop

API Calling:

using Fengb3.EasyCodeBuilder.Csharp;
using Fengb3.EasyCodeBuilder.Csharp.OptionConfigurations;

// Create a method using KeywordConfigurator for public access
var classOption = new TypeOption()
    .WithTypeKind(TypeOption.Type.Class)
    .WithName("NumberPrinter");

classOption.Public.Method(method => {
    method.WithName("PrintNumbers")
          .WithReturnType("void")
          .For(@for => {
              @for.WithInitializer("int i = 0")
                  .WithCondition("i < 10")
                  .WithIterator("i++")
                  .AppendLine("Console.WriteLine(i);");
          });
});

var code = classOption.Build();

Generated Code:

class NumberPrinter
{
  public void PrintNumbers()
  {
    for (int i = 0; i < 10; i++)
    {
      Console.WriteLine(i);
    }
  }
}

Control Structures - Switch Statement

API Calling:

using Fengb3.EasyCodeBuilder.Csharp;
using Fengb3.EasyCodeBuilder.Csharp.OptionConfigurations;

// Create a class with a public method using KeywordConfigurator
var classOption = new TypeOption()
    .WithTypeKind(TypeOption.Type.Class)
    .WithName("DayHelper");

classOption.Public.Method(method => {
    method.WithName("GetDayName")
          .WithReturnType("string")
          .WithParameters("int day");  // WithParameters for methods
    
    method.Switch(@switch => {
        @switch.Expression = "day";
        @switch.Case(@case => {
            @case.Value = "1";
            @case.AppendLine("return \"Monday\";");
        });
        @switch.Case(@case => {
            @case.Value = "2";
            @case.AppendLine("return \"Tuesday\";");
        });
        @switch.Default(@default => 
            @default.AppendLine("return \"Unknown\";")
        );
    });
});

var code = classOption.Build();

Generated Code:

class DayHelper
{
  public string GetDayName(int day)
  {
    switch (day)
    {
      case 1:
      {
        return "Monday";
      }
      case 2:
      {
        return "Tuesday";
      }
      default:
      {
        return "Unknown";
      }
    }
  }
}

🎯 Key Concepts

Option-Based Configuration

EasyCodeBuilder v0.1.0 uses a configuration-based approach where you:

  1. Create option objects - Each code construct has a corresponding option class
  2. Configure properties - Use With* methods or set properties directly
  3. Add children - Nest options within options to build complex structures
  4. Build the code - Call .Build() to generate the final code string

Extension Methods

The library provides fluent extension methods for common operations:

  • WithName(), WithKeyword(), WithType() - Configure basic properties
  • Public, Private, Internal, Static - Keyword configurator properties for fluent keyword specification
  • KeywordConfigurator - Access the keyword configurator for advanced chaining with Parent property
  • Using() - Add using statements
  • Namespace(), Class(), Method() - Add structural elements
  • AutoProperty(), Constructor() - Add members
  • For(), While(), If(), Switch() - Add control flow
  • AppendLine() - Add raw code lines

Building Code

There are two main ways to build code:

  1. Direct building from options:

    var option = new TypeOption().WithName("MyClass");
    var code = option.Build();
  2. Using the Code.Create() entry point:

    var code = Code.Create()
        .Using("System")
        .Namespace(ns => { ... })
        .Build();

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ”— Links


Made with ❀️ by Bohan Feng

About

A library for dynamic code generation, supporting Multiple Languages

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages