⚡ Source Generators = Build-Time Magic
Runtime reflection yavaştır. C# Source Generators ile build-time code generation yapın.
🎯 Source Generator Implementation
[Generator]
public class HelloSourceGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
// No initialization needed
}
public void Execute(GeneratorExecutionContext context)
{
// 1. Source Code Generation
var source = @"
namespace Generated
{
public static class HelloWorld
{
public static string SayHello() => "Hello from Source Generator!";
}
}";
context.AddSource("HelloWorld.g.cs", source);
// 2. Attribute-Based Generation
foreach (var type in context.Compilation.SyntaxTrees)
{
// Parse and generate
}
}
}
// 3. Using Generated Code
var message = Generated.HelloWorld.SayHello();
Console.WriteLine(message); // Hello from Source Generator!
// 4. Attribute Example
[AttributeUsage(AttributeTargets.Class)]
public class GenerateToStringAttribute : Attribute { }
[GenerateToString]
public partial class User
{
public string Name { get; set; }
public int Age { get; set; }
}
// Generated code: partial class User with ToString override
✅ Source Generator Kullanım Alanları
- ✓ Auto-generated DTO’lar
- ✓ Serialization code
- ✓ Database mapping
- ✓ Dependency injection registration
- ✓ Performance-critical code
Source Generators, C#’ın en güçlü özelliklerinden biridir. Reflection’ı build-time’a taşıyarak performance kazanın.
