Reflection in C#

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

  • Inspecting Assemblies – Load and examine assemblies dynamically.
  • Retrieving Type Information – Get details about classes, methods, properties, and attributes.
  • Invoking Methods Dynamically – Call methods on objects without knowing their types at compile time.
  • Creating Objects at Runtime – Instantiate classes dynamically.
  • Accessing Private Members – (For debugging/testing purposes) Access private fields and methods.

Key Reflection Classes

  • Assembly – Represents a .NET assembly and allows loading assemblies dynamically.
  • Type – Provides metadata about a class, struct, interface, or enum.
  • PropertyInfo – Represents a property of a class.
  • MethodInfo – Represents a method of a class.
  • FieldInfo – Represents a field of a class.
  • ConstructorInfo – Provides details about constructors.

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!

要查看或添加评论,请登录

Niyati Kaneriya的更多文章

社区洞察