What is reflection in C#?
Answer
Reflection is the ability to inspect and manipulate types, members, and objects at runtime. The System.Reflection namespace provides APIs to examine assembly metadata. Common uses: typeof(MyClass).GetProperties() (inspect properties), obj.GetType().GetMethod("Run").Invoke(obj, args) (invoke method dynamically), Activator.CreateInstance(type) (create instance from type). Used by: ORMs (EF Core maps columns to properties), serializers (JSON.NET, System.Text.Json), DI containers, test frameworks, attribute processing, and code generation. Drawbacks: (1) Performance: significantly slower than direct calls. (2) Type safety: errors are runtime, not compile-time. (3) AOT incompatibility: reflection can break in Native AOT scenarios. Alternatives: source generators (C# 9+) — generate code at compile time, avoiding runtime reflection. Expression trees: compile-time-safe dynamic code execution.
More C# / .NET Questions
View all →- Intermediate What is ASP.NET Core and how does it differ from ASP.NET Framework?
- Intermediate What is middleware in ASP.NET Core?
- Intermediate What is dependency injection in ASP.NET Core?
- Intermediate What is Entity Framework Core?
- Intermediate What is the difference between eager, lazy, and explicit loading in EF Core?