Generating ToString from classes
This is how you can use CommonCodeGenerator .
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="CommonCodeGenerator" Version="0.2.0" />
<PackageReference Include="CommonCodeGenerator.SourceGenerator" Version="0.2.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>
The code that you will use is
using ToStringData;
Console.WriteLine("Hello, World!");
Person person = new ();
person.FirstName = "Andrei";
person.LastName = "Ignat";
Console.WriteLine(person.ToString());
using CommonCodeGenerator;
namespace ToStringData;
[GenerateToString]
internal partial class Person
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
[IgnoreToString]
public int Age { get; set; }
}
The code that is generated is
// <auto-generated />
#nullable disable
namespace ToStringData
{
partial class Person
{
public override string ToString()
{
var handler = new global::System.Runtime.CompilerServices.DefaultInterpolatedStringHandler(0, 0, default, stackalloc char[256]);
handler.AppendLiteral("Person ");
handler.AppendLiteral("{ ");
handler.AppendLiteral("FirstName = ");
handler.AppendFormatted(FirstName);
handler.AppendLiteral(", ");
handler.AppendLiteral("LastName = ");
handler.AppendFormatted(LastName);
handler.AppendLiteral(" }");
return handler.ToStringAndClear();
}
}
}
Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/CommonCodeGenerator