⚙️ Key Takeaways: Source generators let you analyze and generate C# code at compile time. Build better DTOs, MVVM, and automated code without reflection.
Writing repetitive code is boring. Source Generators write it for you at compile time.
🚀 Create a Source Generator
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;
[Generator]
public class PropertyNotifyGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
// ✅ Register for syntax notifications
context.RegisterForSyntaxNotifications(() => new ClassDeclarationReceiver());
}
public void Execute(GeneratorExecutionContext context)
{
// ✅ Find all classes with [GenerateNotify] attribute
var receiver = (ClassDeclarationReceiver)context.SyntaxReceiver;
foreach (var classDeclaration in receiver.CandidateClasses)
{
// ✅ Generate INotifyPropertyChanged implementation
var source = GeneratePropertyChangedClass(classDeclaration);
context.AddSource($"{classDeclaration.Identifier.Text}.g.cs", SourceText.From(source, Encoding.UTF8));
}
}
}
// ✅ Receiver to find classes with attribute
public class ClassDeclarationReceiver : ISyntaxReceiver
{
public List<ClassDeclarationSyntax> CandidateClasses { get; } = new();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax classDeclaration
&& classDeclaration.AttributeLists
.SelectMany(attr => attr.Attributes)
.Any(attr => attr.Name.ToString() == "GenerateNotify"))
{
CandidateClasses.Add(classDeclaration);
}
}
}
💡 Real-World: DTO Generator
[Generator]
public class DtoGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
// Find all entities with [GenerateDto] attribute
var entities = context.Compilation
.GetSymbolsWithName(name => true)
.OfType<INamedTypeSymbol>()
.Where(s => s.GetAttributes()
.Any(a => a.AttributeClass.Name == "GenerateDtoAttribute"));
foreach (var entity in entities)
{
var source = GenerateDto(entity);
context.AddSource($"{entity.Name}Dto.g.cs", SourceText.From(source, Encoding.UTF8));
}
}
private string GenerateDto(INamedTypeSymbol entity)
{
var properties = entity.GetMembers()
.OfType<IPropertySymbol>()
.Where(p => p.DeclaredAccessibility == Accessibility.Public);
var sb = new StringBuilder();
sb.AppendLine($"public class {entity.Name}Dto");
sb.AppendLine("{");
foreach (var prop in properties)
{
var typeName = prop.Type.ToDisplayString();
var propName = prop.Name;
sb.AppendLine($" public {typeName} {propName} {{ get; set; }}");
}
sb.AppendLine("}");
return sb.ToString();
}
}
📊 Source Generator Benefits
| Feature | Reflection | Source Generators |
|---|---|---|
| Performance | ❌ Runtime overhead | ✅ Zero overhead |
| Compile-time | ❌ Runtime errors | ✅ Compile errors |
| IDE Support | ❌ Limited | ✅ Full IntelliSense |
| Debugging | ❌ Hard | ✅ Easy |




