Source Generators | .NET8 | CSharp
- Source Generators | .NET8 | CSharp
[Generator]
public class HelloWorldGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
// Register any callbacks here
}
public void Execute(GeneratorExecutionContext context)
{
// Create the source code to inject
string sourceCode = @"
using System;
namespace HelloWorldGenerated
{
public static class HelloWorld
{
public static void SayHello() =>
Console.WriteLine(""Hello from the generated code!"");
}
}";
// Add the source code to the compilation
context.AddSource(
"HelloWorldGenerated",
SourceText.From(sourceCode, Encoding.UTF8)
);
}
}