9️⃣ C# Advanced Concepts
Estimated reading: 3 minutes 39 views

πŸš€ C# Reflection – Inspect and Manipulate Code at Runtime


🧲 Introduction – Why Use Reflection in C#?

Sometimes in advanced development, you need to interact with types and members without knowing them at compile time. This is where C# Reflection comes inβ€”it lets you inspect assemblies, types, properties, methods, and attributes dynamically at runtime. It’s essential for frameworks, plugin systems, serialization tools, and more.

🎯 In this guide, you’ll learn:

  • What reflection is in C#
  • How to inspect types, methods, and properties dynamically
  • How to invoke methods and access attributes
  • Real-world use cases and performance tips

πŸ” Core Concept – What Is Reflection?

Reflection is a feature in C# that allows your program to introspect and interact with its own structureβ€”such as assemblies, types, methods, fields, and attributesβ€”at runtime using the System.Reflection namespace.


🧱 Basic Reflection Example

Type type = typeof(string);
Console.WriteLine("Type Name: " + type.FullName);

πŸ“˜ Type objects describe metadata about a class, struct, enum, etc.


πŸ” Inspecting Type Members

Type type = typeof(Console);
MethodInfo[] methods = type.GetMethods();

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

πŸ“˜ Use Case: List all methods in a class dynamically.


πŸ” Getting and Setting Property Values

var person = new Person { Name = "Alice" };
Type type = person.GetType();
PropertyInfo prop = type.GetProperty("Name");

Console.WriteLine(prop.GetValue(person)); // Output: Alice
prop.SetValue(person, "Bob");
Console.WriteLine(person.Name); // Output: Bob

πŸ“˜ Use Case: Create dynamic property mappers or model binders.


πŸ“Œ Invoking Methods with Reflection

MethodInfo method = type.GetMethod("ToUpper");
string result = (string)method.Invoke("hello", null);
Console.WriteLine(result); // Output: HELLO

πŸ“˜ You can even call methods on strings, objects, or custom classes using reflection.


🎯 Accessing Custom Attributes

[Info("Sample class")]
class Sample { }

var attributes = typeof(Sample).GetCustomAttributes(false);

foreach (var attr in attributes)
{
    Console.WriteLine(attr.GetType().Name);
}

πŸ“˜ Use Case: Read annotations used for configuration, documentation, or behavior control.


🧩 Assembly-Level Reflection

Assembly assembly = Assembly.GetExecutingAssembly();
foreach (Type t in assembly.GetTypes())
{
    Console.WriteLine(t.FullName);
}

πŸ“˜ Useful for loading plugins, finding all types, or building dependency injection containers.


πŸ’‘ Best Practices & Tips

πŸ’‘ Tip: Use reflection for tasks like logging, serialization, UI generation, or tooling.

⚠️ Pitfall: Reflection is slower than regular code. Use it sparingly in performance-critical paths.

πŸ“˜ Best Practice: Always cache reflection results (like PropertyInfo, MethodInfo) when used frequently.


πŸ› οΈ Real-World Use Cases

  • πŸ”Œ Plugin and module loading
  • πŸ§ͺ Unit test runners (e.g., MSTest, NUnit)
  • 🧾 Serialization frameworks (e.g., JSON.NET)
  • πŸ“‹ UI generation based on models
  • βš™οΈ Dependency injection frameworks (e.g., ASP.NET Core DI)

πŸ“Œ Summary – Recap & Next Steps

🧡 Key Takeaways:

  • Reflection allows your code to inspect itself and interact with types dynamically.
  • Use it to access types, properties, methods, and attributes at runtime.
  • Use wisely to avoid performance overhead.

βš™οΈ Real-world relevance: C# Reflection powers major libraries like Entity Framework, AutoMapper, NUnit, and ASP.NET Core itself.


❓ FAQ Section

❓ What namespace is needed for Reflection?
βœ… System.Reflection


❓ Is Reflection safe to use in production?
βœ… Yes, but it should be used efficiently and securely (e.g., avoid exposing private data).


❓ Can I invoke private members using reflection?
βœ… Yes, using BindingFlags.NonPublic | BindingFlags.Instance, but use with caution.


❓ Can reflection be used to load types from other assemblies?
βœ… Absolutely. Use Assembly.Load() or Assembly.LoadFrom() to dynamically load DLLs.


❓ Does reflection work with generics?
βœ… Yes, but you must use MakeGenericType() to construct a closed generic type.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸš€ C# Reflection

Or Copy Link

CONTENTS
Scroll to Top