Advertisement
Advanced .NET, Assemblies & NuGet

How does reflection allow inspecting an assembly's types and metadata at runtime, and what are common uses?

Short answer

System.Reflection APIs let you load an assembly (Assembly.Load, Assembly.LoadFrom) and enumerate its types, methods, properties, and custom attributes at runtime without compile-time knowledge of them -- powering scenarios like plugin discovery (finding all types implementing an…

Save .NET mock interview
Advertisement
AModel answer
System.Reflection APIs let you load an assembly (Assembly.Load, Assembly.LoadFrom) and enumerate its types, methods, properties, and custom attributes at runtime without compile-time knowledge of them -- powering scenarios like plugin discovery (finding all types implementing an interface), ORM mapping (reading property metadata to generate SQL), and dependency injection container auto-registration (scanning assemblies for service implementations).
var assembly = Assembly.LoadFrom("MyPlugin.dll");
var pluginTypes = assembly.GetTypes()
    .Where(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsInterface);

foreach (var type in pluginTypes) {
    var instance = (IPlugin)Activator.CreateInstance(type);
    instance.Execute();
}
Real-world example
A DI container auto-registration extension scans all loaded assemblies via reflection at startup, automatically registering every class implementing a marker interface like IScopedService, eliminating dozens of manual registration lines.
Likely follow-ups
  • What's the performance cost of reflection-heavy code, and how does source generation help?
  • Why is heavy reflection incompatible with Native AOT trimming?
Related topics