Understanding C# Reflection: A Comprehensive Beginner's Guide
Understanding C# Reflection: A Comprehensive Beginner's Guide
Reflection in C# is a powerful feature that enables developers to inspect and interact with the metadata of types, methods, and assemblies at runtime. This guide delves into the core concepts of C# Reflection, its practical applications, and illustrative examples to enhance your understanding.
Key Concepts
- What is Reflection?
- Reflection allows you to obtain information about types, methods, properties, and events in C#.
- It facilitates the dynamic creation of type instances, method invocation, and property access.
- Namespaces
- The
System.Reflection
namespace houses classes and methods essential for working with reflection.
- The
Uses of Reflection
- Inspecting Types
- Retrieve detailed information about a class, including its methods, properties, and attributes.
- Dynamic Method Invocation
- Invoke methods on objects without needing to know their types at compile time.
- Creating Instances
- Instantiate objects of types at runtime using their constructors.
- Accessing Attributes
- Read custom attributes that are applied to classes, methods, and properties.
Basic Example
Inspecting a Class
Below is an example demonstrating how to use reflection to inspect a class named MyClass
.
using System;
using System.Reflection;
public class MyClass
{
public void MyMethod() { }
}
class Program
{
static void Main()
{
Type myType = typeof(MyClass);
// Get the methods of MyClass
MethodInfo[] methods = myType.GetMethods();
Console.WriteLine("Methods in MyClass:");
foreach (var method in methods)
{
Console.WriteLine(method.Name);
}
}
}
Output:
Methods in MyClass:
MyMethod
Creating an Instance Dynamically
You can create an instance of MyClass
using reflection as shown below:
Type myType = typeof(MyClass);
object myObject = Activator.CreateInstance(myType);
Invoking a Method Dynamically
To invoke MyMethod
from an instance of MyClass
, use the following code:
MethodInfo methodInfo = myType.GetMethod("MyMethod");
methodInfo.Invoke(myObject, null);
Conclusion
Reflection in C# is a potent technique that significantly enhances programming flexibility. By grasping its key concepts, developers can effectively inspect types, invoke methods, and manipulate objects at runtime, leading to more dynamic and adaptable applications.