C# Reflection: Examining and Manipulating Code at Runtime
Learn C# through interactive, bite-sized lessons. Build .NET applications with hands-on practice.
Start C# Journey →Reflection is a powerful feature in C# that enables programs to inspect, interact with, and modify their own structure and behavior during runtime. It provides a way to dynamically load assemblies, create instances of types, and invoke methods without compile-time knowledge of their names.
Understanding C# Reflection
At its core, reflection allows you to:
- Examine metadata of types, methods, and properties
- Create instances of classes dynamically
- Invoke methods and access properties at runtime
- Generate new code on the fly
Reflection is particularly useful for building flexible and extensible applications, such as plugin systems or serialization frameworks.
Basic Usage of Reflection
To use reflection in C#, you'll primarily work with the System.Reflection namespace. Here's a simple example of how to get information about a type:
using System;
using System.Reflection;
Type myType = typeof(string);
Console.WriteLine($"Type name: {myType.Name}");
Console.WriteLine($"Is it a class? {myType.IsClass}");
Console.WriteLine($"Base type: {myType.BaseType.Name}");
This code snippet demonstrates how to retrieve basic information about the string type using reflection.
Creating Instances and Invoking Methods
Reflection allows you to create objects and call methods dynamically. Here's an example:
Type listType = typeof(List<int>);
object listInstance = Activator.CreateInstance(listType);
MethodInfo addMethod = listType.GetMethod("Add");
addMethod.Invoke(listInstance, new object[] { 42 });
MethodInfo countProperty = listType.GetProperty("Count").GetGetMethod();
int count = (int)countProperty.Invoke(listInstance, null);
Console.WriteLine($"Count: {count}"); // Output: Count: 1
This example creates a List<int> instance, adds an element using reflection, and then retrieves the count.
Performance Considerations
While reflection is powerful, it comes with performance overhead. Consider these points:
- Reflection operations are slower than direct code execution
- Use caching mechanisms for frequently accessed reflection data
- Prefer compile-time solutions when possible
- Be cautious with reflection in performance-critical sections
Security Implications
Reflection can bypass normal code access security checks. When using reflection, especially with user-supplied input, be mindful of potential security risks. Always validate and sanitize inputs to prevent unauthorized access or code execution.
Related Concepts
To deepen your understanding of C# reflection, explore these related topics:
- C# Attributes: Metadata that can be retrieved via reflection
- C# Generics: Often used in conjunction with reflection for type-safe operations
- C# Assemblies: The building blocks that reflection operates on
Mastering reflection in C# opens up powerful possibilities for creating flexible and dynamic applications. While it's a complex topic, understanding its basics can significantly enhance your C# programming skills.