Glossary / Reflection
Reflection
Reflection inspects assemblies, types, members, and metadata at runtime and can dynamically create instances or invoke members. It enables plugin systems, serializers, dependency injection, and tooling, but trades compile-time safety and performance for runtime flexibility and can complicate trimming, Native AOT, security, and refactoring.
Metadata inspection and invocation
Type type = typeof(MyService);
foreach (var method in type.GetMethods()) Console.WriteLine(method.Name);
Type, Assembly, and MemberInfo APIs expose metadata. Invocation via MethodInfo.Invoke uses object arrays and can wrap target exceptions in TargetInvocationException; reflection can also create generic types, inspect attributes, and invoke constructors. Prefer strongly typed delegates or generated code when repeated invocation is performance-sensitive.
Reflection-based discovery may be invisible to the trimmer or AOT compiler, which can remove members thought unused. Use annotations such as DynamicallyAccessedMembers, explicit preservation, source generation, or registration where appropriate. Reflection access is not a security sandbox; private-member access depends on runtime and trust constraints.
Engineering guidance
Use reflection at boundaries, cache metadata/delegates, validate plugin inputs, and provide clear diagnostics. Prefer source generators or explicit registration for known compile-time sets. Test trimmed and AOT deployments if reflection is used, not only standard JIT builds.
Interview questions
- What does reflection provide? Runtime inspection and dynamic interaction with metadata-described types/members.
- Why slower than direct calls? Lookup, argument adaptation, boxing, and invocation overhead, though caching/delegates can help.
- What is TargetInvocationException? A wrapper commonly thrown when reflected target invocation throws.
- Why does trimming break reflection? Members only used dynamically may be removed as statically unreachable.
- When use source generation instead? When targets are known at build time and generated code improves safety/performance/AOT compatibility.