Reflection in C#
Introduction
Reflection in C# is a powerful feature that allows you to inspect and manipulate types, methods, properties, and attributes at runtime. It enables dynamic programming scenarios, such as dependency injection, plugin architectures, and runtime type discovery.
What is Reflection?
Reflection is the ability of a program to examine and modify its structure and behavior at runtime. It is part of the System.Reflection namespace in .NET and provides classes to work with metadata and type information.
Common Use Cases
Key Reflection Classes
Examples
1. Getting Type Information
using System;
using System.Reflection;
class Program
{
static void Main()
{
Type type = typeof(DemoClass);
Console.WriteLine("Class Name: " + type.Name);
Console.WriteLine("Namespace: " + type.Namespace);
}
}
class DemoClass {}
2. Listing Methods of a Class
Type type = typeof(string);
MethodInfo[] methods = type.GetMethods();
foreach (var method in methods)
{
Console.WriteLine(method.Name);
}
3. Invoking a Method Dynamically
class Demo
{
public void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
}
Type type = typeof(Demo);
object obj = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("Greet");
method.Invoke(obj, new object[] { "John" });
4. Accessing Private Members
class PrivateDemo
{
private string secret = "Hidden Message";
}
Type type = typeof(PrivateDemo);
FieldInfo field = type.GetField("secret", BindingFlags.NonPublic | BindingFlags.Instance);
object obj = Activator.CreateInstance(type);
Console.WriteLine(field.GetValue(obj));
Performance Considerations
Reflection is powerful but comes with performance overhead. It should be used sparingly in performance-critical applications. Caching metadata results can help mitigate the cost.
Conclusion
Reflection in C# is an essential tool for dynamic programming, enabling capabilities like dependency injection, runtime type discovery, and plugin loading. While powerful, developers should use it carefully to avoid performance issues and maintain code readability.
Have you used Reflection in your projects? Share your experiences in the comments!