9.Reflection & Dynamic Features - aniketmulmule/web_Project GitHub Wiki
Hereโs a deep dive into Reflection and Dynamic Features in C#, tailored for 8+ years of experience, with code examples, advanced use cases, and interview-level insights.
Reflection is a powerful feature in .NET that allows you to inspect and interact with metadata, types, assemblies, and members at runtime.
-
Late binding (e.g., plug-in loading)
-
Inspecting attributes and methods
-
Creating objects dynamically
-
Serialization frameworks
-
Testing/mocking
Class | Purpose |
---|---|
Type | Info about class/struct/interface |
MethodInfo | Info about methods |
PropertyInfo | Info about properties |
ConstructorInfo | Info about constructors |
Assembly | Load and inspect assemblies |
Would you like:
-
๐ A PDF version of this for your study kit?
-
๐งช Practice exercises or quizzes?
-
๐ฏ Mock interview questions with sample answers?
Let me know โ happy to prepare those!
Hereโs a **deep dive into Reflection and Dynamic Features in C#**, tailored for **8+ years of experience**, with code examples, advanced use cases, and **interview-level insights**.Reflection is a powerful feature in .NET that allows you to inspect and interact with metadata, types, assemblies, and members at runtime.
- Late binding (e.g., plug-in loading)
- Inspecting attributes and methods
- Creating objects dynamically
- Serialization frameworks
- Testing/mocking
Class | Purpose |
---|---|
Type |
Info about class/struct/interface |
MethodInfo |
Info about methods |
PropertyInfo |
Info about properties |
ConstructorInfo |
Info about constructors |
Assembly |
Load and inspect assemblies |
Type type = typeof(string);
Console.WriteLine(type.FullName); // System.String
foreach (var method in type.GetMethods())
{
Console.WriteLine(method.Name);
}
Type t = Type.GetType("System.Text.StringBuilder");
object obj = Activator.CreateInstance(t);
MethodInfo method = t.GetMethod("Append", new[] { typeof(string) });
method.Invoke(obj, new object[] { "Hello" });
[Obsolete("Use NewMethod")]
public void OldMethod() { }
var method = typeof(MyClass).GetMethod("OldMethod");
var attr = method.GetCustomAttribute<ObsoleteAttribute>();
Console.WriteLine(attr.Message); // Use NewMethod
- Reflection is slower than direct access.
- Bypasses compile-time checking โ runtime errors.
- Difficult to maintain and test.
- Use only where dynamic behavior is essential.
Introduced in C# 4.0 โ runtime-bound type.
dynamic x = "hello";
Console.WriteLine(x.Length); // Works, but resolved at runtime
x = 123;
Console.WriteLine(x.Length); // Runtime error!
-
Bypasses IntelliSense and compile-time type checks
-
Useful for:
- Interop with COM/JavaScript
- Reflection-like scenarios
- JSON/XML dynamic parsing
Allows you to add members at runtime.
dynamic obj = new ExpandoObject();
obj.Name = "Aniket";
obj.SayHello = (Action)(() => Console.WriteLine($"Hi {obj.Name}"));
obj.SayHello(); // Hi Aniket
Topic | Expectation |
---|---|
Reflection | Use cases, benefits, risks, examples |
Type , MethodInfo , Activator
|
Know how to dynamically invoke |
dynamic vs object
|
dynamic resolves at runtime; object requires casting |
Performance concerns | Reflection is slower and error-prone |
Real-life usage | Logging frameworks, IoC containers, plugin systems |
Question | Ideal Answer |
---|---|
When have you used reflection in real projects? | Logging, plugin architecture, unit test frameworks |
What is the difference between typeof , GetType() , and Type.GetType() ? |
See table below |
What is the risk of using dynamic ? |
No compile-time checking; runtime failures |
How does reflection differ from dynamic ? |
Reflection uses metadata; dynamic is runtime binding |
Syntax | Purpose |
---|---|
typeof(MyClass) |
At compile time |
obj.GetType() |
At runtime |
Type.GetType("Namespace.MyClass") |
From string (assembly must be loaded) |
Load DLLs at runtime and find all classes implementing an interface:
Assembly asm = Assembly.LoadFrom("MyPlugin.dll");
var types = asm.GetTypes().Where(t => typeof(IMyPlugin).IsAssignableFrom(t));
Uses reflection to get property names, types, and values.
Topic | Link |
---|---|
Microsoft Docs - Reflection | https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection |
Reflection Deep Dive (Jon Skeet) | https://csharpindepth.com/ |
ExpandoObject & dynamic types | https://learn.microsoft.com/en-us/dotnet/api/system.dynamic |
Book: C# in Depth by Jon Skeet | Great for advanced language features |
- โ
Cache
Type
,MethodInfo
results if reused. - โ Avoid overusing
dynamic
โ leads to fragile code. - โ Use reflection only when no better static alternative exists.
- โ Always validate dynamic method names or types before invoking.
Feature | Summary |
---|---|
Reflection | Runtime type inspection/manipulation |
dynamic |
Runtime binding (compiler skips type checking) |
ExpandoObject | Add/remove members at runtime |
Use Cases | Plugin loading, serialization, low-code systems |
Alternatives | Generics, expression trees, interface-based design |
Would you like:
- ๐ A PDF version of this for your study kit?
- ๐งช Practice exercises or quizzes?
- ๐ฏ Mock interview questions with sample answers?
Let me know โ happy to prepare those!