| name | RossLean.StringificationGenerator |
| nuget | https://www.nuget.org/packages/RossLean.StringificationGenerator/ |
| link | https://github.com/RossLean/RossLean/ |
| author | Alex Kalfakakos |
Generating constructor code as string
This is how you can use RossLean.StringificationGenerator .
The code that you start with is
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RossLean.StringificationGenerator" Version="1.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="RossLean.StringificationGenerator.Core" Version="1.0.0" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>
The code that you will use is
using Code2String; using RossLean.StringificationGenerator.Generated; Person person = new Person("Andrei","Ignat"); string personString = ConstructionCodeGeneration.ForPerson(person); Console.WriteLine(personString);
using RossLean.StringificationGenerator.Core;
namespace Code2String;
[GenerateConstructionCode]
public record Person(string firstName,string lastName)
{
}
The code that is generated is
using Code2String;
using RossLean.StringificationGenerator.Core;
using System.Text;
namespace RossLean.StringificationGenerator.Generated;
public partial class ConstructionCodeGeneration : BaseConstructionCodeGeneration
{
public static string ForPerson(Person person)
{
return $$"""
new Person({{StringLiteral(person.firstName)}},{{StringLiteral(person.lastName)}})
""";
}
public static void AppendPerson(Person person,StringBuilder builder)
{
builder.Append($$"""
new Person({{StringLiteral(person.firstName)}},{{StringLiteral(person.lastName)}})
""");
}
public static string ForPersonTargetTyped(Person person)
{
return $$"""
new({{StringLiteral(person.firstName)}},{{StringLiteral(person.lastName)}})
""";
}
public static void AppendPersonTargetTyped(Person person,StringBuilder builder)
{
builder.Append($$"""
new({{StringLiteral(person.firstName)}},{{StringLiteral(person.lastName)}})
""");
}
}
Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/RossLean.StringificationGenerator
Leave a Reply