Skip to content

Reflection

Reflection provides a way to inspect, modify, and create types, methods, and fields at runtime. It enables dynamic programming scenarios and is particularly useful for building frameworks and tools.

Type Information

Type information allows you to examine the structure of classes and objects at runtime, including their properties, methods, and attributes.

csharp
Type type = typeof(string);
PropertyInfo[] properties = type.GetProperties();
MethodInfo[] methods = type.GetMethods();

Creating Instances

Reflection enables dynamic creation of objects from their type information, useful for plugin architectures and dependency injection scenarios.

csharp
Type type = Type.GetType("Namespace.ClassName");
object instance = Activator.CreateInstance(type);

Invoking Methods

Dynamic method invocation allows you to call methods on objects using their names as strings, enabling flexible and adaptable code.

csharp
MethodInfo method = type.GetMethod("MethodName");
object result = method.Invoke(instance, new object[] { param1, param2 });