⚙️ C# / .NET Intermediate

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.