C# › Attributes & Reflection

How would you use System.Reflection.Emit or source generators as faster, more modern alternatives to runtime reflection for code generation scenarios?

Advanced

Answer

System.Reflection.Emit lets you generate and JIT-compile IL code dynamically at runtime for maximum flexibility (though complex to write); modern .NET increasingly favors SOURCE GENERATORS instead, which run at COMPILE TIME to generate real C# source code based on your attributes/types, producing fully AOT-compatible, reflection-free code with zero runtime overhead — the direction libraries like System.Text.Json's source-generated serializers have moved toward.
// Source generator approach (conceptual): attribute triggers compile-time code generation
[JsonSerializable(typeof(User))]
partial class AppJsonContext : JsonSerializerContext { }
// The compiler generates a real, reflection-free serializer for User at BUILD time
Real-world example Choosing source generators over runtime reflection for a library that needs to support Native AOT compilation, where reflection is heavily restricted.

Common follow-ups: Why does Native AOT compilation specifically struggle with (or outright disallow) certain kinds of runtime reflection?