⚙️ Write Code That Writes Code
Reflection is slow. Source generators run at compile time. Generate JSON serializers, INotifyPropertyChanged, mappers — zero runtime overhead.
📝 Simple Source Generator
[Generator]
public class HelloWorldGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context) { }
public void Execute(GeneratorExecutionContext context)
{
string source = @"
namespace Generated
{
public static class HelloWorld
{
public static void SayHello() =>
Console.WriteLine("Hello from generated code!");
}
}";
context.AddSource("HelloWorld.g.cs", source);
}
}
// Usage in any project referencing the generator
Generated.HelloWorld.SayHello();
🎯 Real-World: INotifyPropertyChanged
// Attribute
[AttributeUsage(AttributeTargets.Class)]
public class GenerateNotifyPropertyChangedAttribute : Attribute { }
// Generator finds classes with attribute and implements INotifyPropertyChanged
[GenerateNotifyPropertyChanged]
public partial class Person
{
private string _name;
public string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
}
// Generator adds:
// - SetProperty method
// - PropertyChanged event
// - OnPropertyChanged method
💡 Use Cases
- JSON serialization (System.Text.Json source generator)
- Dependency Injection registration
- AutoMapper without reflection
- Regex compilation (RegexGenerator)
- Logging message templates
“Switched from Reflection-based JSON to source generator. Serialization went from 2ms to 0.1ms. No more reflection overhead. Source generators are underutilized.”
