$npx -y skills add wshaddix/dotnet-skills --skill dotnet-csharp-source-generatorsCreating source generators. IIncrementalGenerator, GeneratedRegex, LoggerMessage, STJ source-gen.
| 1 | # dotnet-csharp-source-generators |
| 2 | |
| 3 | Guidance for both **creating** and **consuming** Roslyn source generators in .NET. Creating: `IIncrementalGenerator`, syntax providers, semantic analysis, emit patterns, diagnostic reporting, testing with `CSharpGeneratorDriver`. Consuming: `[GeneratedRegex]`, `[LoggerMessage]`, System.Text.Json source generation, `[JsonSerializable]`. |
| 4 | |
| 5 | Cross-references: [skill:dotnet-csharp-modern-patterns] for partial properties and related C# features, [skill:dotnet-csharp-coding-standards] for naming conventions. |
| 6 | |
| 7 | --- |
| 8 | |
| 9 | ## Creating Source Generators |
| 10 | |
| 11 | ### Project Setup |
| 12 | |
| 13 | Source generators are shipped as analyzers targeting `netstandard2.0`. |
| 14 | |
| 15 | ```xml |
| 16 | <Project Sdk="Microsoft.NET.Sdk"> |
| 17 | <PropertyGroup> |
| 18 | <TargetFramework>netstandard2.0</TargetFramework> |
| 19 | <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> |
| 20 | <IsRoslynComponent>true</IsRoslynComponent> |
| 21 | <LangVersion>latest</LangVersion> |
| 22 | </PropertyGroup> |
| 23 | |
| 24 | <ItemGroup> |
| 25 | <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" /> |
| 26 | <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0" PrivateAssets="all" /> |
| 27 | </ItemGroup> |
| 28 | </Project> |
| 29 | ``` |
| 30 | |
| 31 | > **Always target `netstandard2.0`.** Generators load into the compiler process, which requires this TFM for compatibility. Use `LangVersion>latest` to write modern C# in the generator itself. |
| 32 | |
| 33 | ### `IIncrementalGenerator` (Preferred) |
| 34 | |
| 35 | Always use `IIncrementalGenerator` over the legacy `ISourceGenerator`. Incremental generators are cache-aware and only re-run when inputs change, making them significantly faster in IDE scenarios. |
| 36 | |
| 37 | ```csharp |
| 38 | [Generator] |
| 39 | public sealed class AutoNotifyGenerator : IIncrementalGenerator |
| 40 | { |
| 41 | public void Initialize(IncrementalGeneratorInitializationContext context) |
| 42 | { |
| 43 | // Step 1: Filter syntax nodes to candidate fields |
| 44 | var fieldDeclarations = context.SyntaxProvider |
| 45 | .ForAttributeWithMetadataName( |
| 46 | "MyLib.AutoNotifyAttribute", |
| 47 | predicate: static (node, _) => node is FieldDeclarationSyntax, |
| 48 | transform: static (ctx, _) => GetFieldInfo(ctx)) |
| 49 | .Where(static info => info is not null) |
| 50 | .Select(static (info, _) => info!.Value); |
| 51 | |
| 52 | // Step 2: Group fields by containing type, then emit one file per type |
| 53 | context.RegisterSourceOutput(fieldDeclarations.Collect(), |
| 54 | static (spc, fields) => Execute(fields, spc)); |
| 55 | } |
| 56 | |
| 57 | private static FieldInfo? GetFieldInfo( |
| 58 | GeneratorAttributeSyntaxContext context) |
| 59 | { |
| 60 | var fieldSymbol = context.TargetSymbol as IFieldSymbol; |
| 61 | if (fieldSymbol is null) |
| 62 | return null; |
| 63 | |
| 64 | var containingType = fieldSymbol.ContainingType; |
| 65 | |
| 66 | // Use fully qualified type name to handle generic and nested types |
| 67 | var fullTypeName = containingType.ToDisplayString( |
| 68 | SymbolDisplayFormat.FullyQualifiedFormat |
| 69 | .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted)); |
| 70 | |
| 71 | return new FieldInfo( |
| 72 | fieldSymbol.ContainingNamespace.IsGlobalNamespace |
| 73 | ? "" |
| 74 | : fieldSymbol.ContainingNamespace.ToDisplayString(), |
| 75 | containingType.Name, |
| 76 | fullTypeName, |
| 77 | fieldSymbol.Name, |
| 78 | fieldSymbol.Type.ToDisplayString()); |
| 79 | } |
| 80 | |
| 81 | private static void Execute( |
| 82 | ImmutableArray<FieldInfo> fields, |
| 83 | SourceProductionContext context) |
| 84 | { |
| 85 | // Group by fully qualified type name to emit one file per class |
| 86 | foreach (var group in fields.GroupBy(f => f.FullTypeName)) |
| 87 | { |
| 88 | var first = group.First(); |
| 89 | var ns = first.Namespace; |
| 90 | var className = first.ClassName; |
| 91 | var properties = new StringBuilder(); |
| 92 | |
| 93 | foreach (var field in group) |
| 94 | { |
| 95 | var propertyName = GetPropertyName(field.FieldName); |
| 96 | properties.AppendLine($$""" |
| 97 | public {{field.FieldType}} {{propertyName}} |
| 98 | { |
| 99 | get => {{field.FieldName}}; |
| 100 | set |
| 101 | { |
| 102 | if (!global::System.Collections.Generic.EqualityComparer<{{field.FieldType}}>.Default.Equals({{field.FieldName}}, value)) |
| 103 | { |
| 104 | {{field.FieldName}} = value; |
| 105 | PropertyChanged?.Invoke(this, |
| 106 | new global::System.ComponentModel.PropertyChangedEventArgs(nameof({{propertyName}}))); |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | """); |
| 111 | } |
| 112 | |
| 113 | // Handle global namespace (no namespace declaration) |