π 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 :
