The project Coaster is a library that allows easy parsing and formatting of C# source files. Coaster introduces a nice interface to manipulate C# source files, like adding fields, methods, attributes and so on.
dotnet add package Coaster
Example:
Coast.Parse("public class HelloWorld {}");
Coaster provides a nice API to generate C# classes. Here is an example:
var unit = new CUnit { Usings = { "System.Linq", "System", "System.IO" }, Members =
{
new CNamespace { Name = "Example", Members =
{
new CClass { Name = "Person", Members =
{
new CProperty { Type = "int", Name = "Id" },
new CProperty { Type = "string", Name = "FirstName" },
new CProperty { Type = "string", Name = "LastName" }
}
}
}
}
}
};
Console.WriteLine(unit.ToText());
This will produce:
using System;
using System.IO;
using System.Linq;
namespace Example
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Of course, it is possible to mix both approaches (parser and writer) to modify C# code programmatically:
var unit = Coast.Parse("public class SomeClass {}");
var clazz = unit.Members.Cast<CClass>().Single();
clazz.Members.Add(new CMethod { Name = "Main" });
Console.WriteLine(unit.ToText());
Coaster formats the C# Source Code by calling the Format()
method:
var humanCode = "public class MyClass{ private string field;}";
var formattedCode = Coast.Format(humanCode);
Console.WriteLine(formattedCode);
Coaster provides you with a delegate to the C# Source Code:
var func = Compiler.CreateDelegate<Func<string, string>>(unit.ToText());
Console.WriteLine(func("Michael Che"));
Console.WriteLine(func("Fritz Wepp"));
Just run dotnet pack
to build the sources.
This project uses the syntax tree parsing and writing of:
Everything is licensed according to this.