System.Reflection Namespace
Namespace: System.Reflection
Assembly: System.Reflection.dll
Description: Provides classes that allow you to inspect the metadata of assemblies, modules, and types at runtime. Reflection enables you to dynamically discover information about loaded assemblies and to late-bind to members of objects, thereby allowing you to inspect or modify their behavior at runtime. This is particularly useful for building general-purpose or extensible applications.
Classes
-
Assembly
Represents an assembly, which is a partially autonomous unit of code, versioning, and deployment.
-
FieldInfo
Provides access to fields and properties of a type.
-
MethodInfo
Represents a method on a type.
-
ParameterInfo
Describes parameters of methods and constructors.
-
PropertyInfo
Represents a property on a type.
-
TypeInfo
Provides access to type information.
-
ConstructorInfo
Represents a constructor of a type.
Common Scenarios
Loading an Assembly and Inspecting Types
This example demonstrates how to load an assembly dynamically and then iterate through its types.
using System;
using System.Reflection;
public class ReflectionExample
{
public static void Main(string[] args)
{
try
{
// Load an assembly from its path
Assembly assembly = Assembly.LoadFrom("MyLibrary.dll");
// Get all types defined in the assembly
Type[] types = assembly.GetTypes();
Console.WriteLine($"Types found in {assembly.FullName}:");
foreach (Type type in types)
{
Console.WriteLine($"- {type.FullName}");
// Inspect methods
MethodInfo[] methods = type.GetMethods();
Console.WriteLine($" Methods:");
foreach (MethodInfo method in methods)
{
Console.WriteLine($" - {method.Name}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Invoking a Method Dynamically
This example shows how to create an instance of a type and invoke one of its methods using reflection.
using System;
using System.Reflection;
public class DynamicMethodInvocation
{
public static void Main(string[] args)
{
try
{
// Assume MyLibrary.dll contains a class named MyClass with a method named MyMethod
Assembly assembly = Assembly.LoadFrom("MyLibrary.dll");
Type type = assembly.GetType("MyNamespace.MyClass");
if (type != null)
{
// Create an instance of the type
object instance = Activator.CreateInstance(type);
// Get the MethodInfo for the method to invoke
MethodInfo method = type.GetMethod("MyMethod");
if (method != null)
{
// Invoke the method
object result = method.Invoke(instance, null); // null for parameters if no arguments
Console.WriteLine($"Method 'MyMethod' invoked. Result: {result}");
}
else
{
Console.WriteLine("Method 'MyMethod' not found.");
}
}
else
{
Console.WriteLine("Type 'MyNamespace.MyClass' not found.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}