Reflection inspects metadata and interacts with types at runtime. It can discover assemblies, types, attributes, constructors, properties, and methods, and can create or invoke members dynamically. Frameworks use it for dependency registration, serialization, mapping, testing, and plugin discovery. ```csharp [AttributeUsage(AttributeTargets.Class)] public sealed class HandlerAttribute : Attribute { } [Handler] public sealed class PaymentHandler { public Task HandleAsync() => Task.CompletedTask; } var handlers = typeof(PaymentHandler).Assembly.GetTypes() .Where(type => type.GetCustomAttribute<HandlerAttribute>() is not null) .ToArray(); ``` Reflection trades compile-time guarantees and speed for flexibility. Repeated `GetProperty` or `MethodInfo.Invoke` calls in a hot path can allocate and be slower than direct calls; cache metadata or compile delegates when measurement justifies it. Handle `ReflectionTypeLoadException` during broad assembly scanning, avoid invoking untrusted types, and consider trimming or Native AOT: members reachable only through reflection may require annotations or source-generated alternatives.
Prince Yadav · · 0 likes