Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C# Source Generators: Generate Code at Compile Time – The Ultimate Guide

- 23.08.26 - ErcanOPAK

⚙️ 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

Related posts:

C#: Fix the Captured Loop Variable Bug That Makes Every async Lambda Return the Same Value

C#: Fix the Captured Loop Variable Bug That Makes Every async Lambda Return the Same Value

Background Tasks the Right Way

Background Tasks the Right Way

.NET Core JSON Serializer Pitfalls — Why Your Properties Don’t Serialize

.NET Core JSON Serializer Pitfalls — Why Your Properties Don’t Serialize

Views: 16
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Git Bisect: The Bug-Hunting Superpower Every Developer Must Know
ASP.NET Core Endpoint Routing: Deep Dive into the Routing Engine

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com