Attributes & Reflection

11 questions found

What is reflection in C#, and what are its most common practical uses and performance trade-offs?

Intermediate
Reflection lets a running program inspect and manipulate its own types, methods, and properties at runtime, without knowing the exact concrete types at compile time -- common uses include reading metadata (getting a type's full name or its declared members), invoking a method dynamically by name rather than a hardcoded call, instantiating objects whose type is only known at runtime, and powering serialization/DI/testing frameworks that need to work generically across arbitrary types. The trade-off is performance: reflection bypasses many compile-time optimizations and uses slower late-bound dispatch, so it should be used deliberately rather than in a hot, frequently-executed code path.
Type type = typeof(string);
Console.WriteLine(type.FullName); // "System.String"

MethodInfo method = typeof(Console).GetMethod("WriteLine", new[] { typeof(string) });
method.Invoke(null, new object[] { "Hello, Reflection!" }); // dynamically invokes Console.WriteLine
Real-world example A JSON serialization library uses reflection to enumerate an arbitrary object's public properties at runtime and read each one's value, letting it serialize any POJO-like class without needing type-specific serialization code written in advance.

Common follow-ups: Why does Native AOT compilation have limited support for reflection, and what does that mean for serialization libraries?;How do dependency injection containers use reflection to automatically resolve constructor parameters?

Reflection API;Serialization & Deserialization

Showing 11–11 of 11