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.


๐Ÿ” What Is Reflection in C#?

Reflection is a powerful feature in .NET that allows you to inspect and interact with metadata, types, assemblies, and members at runtime.

Key Use Cases:

  • Late binding (e.g., plug-in loading)

  • Inspecting attributes and methods

  • Creating objects dynamically

  • Serialization frameworks

  • Testing/mocking


โš™๏ธ Core Classes in Reflection (Namespace: System.Reflection)

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**.

๐Ÿ” What Is Reflection in C#?

Reflection is a powerful feature in .NET that allows you to inspect and interact with metadata, types, assemblies, and members at runtime.

Key Use Cases:

  • Late binding (e.g., plug-in loading)
  • Inspecting attributes and methods
  • Creating objects dynamically
  • Serialization frameworks
  • Testing/mocking

โš™๏ธ Core Classes in Reflection (Namespace: System.Reflection)

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

๐Ÿงช Examples of Reflection

1. Get Type Info and Members

Type type = typeof(string);
Console.WriteLine(type.FullName); // System.String

foreach (var method in type.GetMethods())
{
    Console.WriteLine(method.Name);
}

2. Instantiate Object Dynamically

Type t = Type.GetType("System.Text.StringBuilder");
object obj = Activator.CreateInstance(t);

3. Invoke Method Dynamically

MethodInfo method = t.GetMethod("Append", new[] { typeof(string) });
method.Invoke(obj, new object[] { "Hello" });

4. Read Attributes

[Obsolete("Use NewMethod")]
public void OldMethod() { }

var method = typeof(MyClass).GetMethod("OldMethod");
var attr = method.GetCustomAttribute<ObsoleteAttribute>();
Console.WriteLine(attr.Message); // Use NewMethod

๐Ÿ’ฅ Risks & Performance

  • Reflection is slower than direct access.
  • Bypasses compile-time checking โ†’ runtime errors.
  • Difficult to maintain and test.
  • Use only where dynamic behavior is essential.

๐Ÿ”ฎ Dynamic Features in C#

1. dynamic Keyword

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

2. ExpandoObject (Namespace: System.Dynamic)

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

๐Ÿง  Interview Perspective

โœ… What You Should Know:

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

๐Ÿงช Common Interview Questions

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

๐Ÿ”„ typeof vs GetType() vs Type.GetType()

Syntax Purpose
typeof(MyClass) At compile time
obj.GetType() At runtime
Type.GetType("Namespace.MyClass") From string (assembly must be loaded)

๐Ÿ” Real-World Examples

1. Plugin System

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));

2. JSON Serialization (e.g., Newtonsoft.Json)

Uses reflection to get property names, types, and values.


๐Ÿ“˜ Resources to Learn More

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

๐Ÿง  Best Practices

  • โœ… 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.

๐Ÿ”š Summary Table

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!

โš ๏ธ **GitHub.com Fallback** โš ๏ธ