C# reflection

‮‬https://www.theitroad.com

Reflection is a powerful feature of C# that allows you to inspect and manipulate types, objects, and assemblies at runtime. With reflection, you can obtain information about a type, such as its name, properties, methods, and events, as well as create instances of types, invoke methods, and access fields and properties dynamically.

The System.Reflection namespace contains classes that allow you to work with reflection in C#. Here are some of the key classes and their uses:

  • Type: Represents a type in C# and provides methods to obtain information about its members, create instances of the type, and invoke its methods.
  • Assembly: Represents an assembly in C# and provides methods to obtain information about its types, modules, and attributes.
  • MethodInfo: Represents a method in C# and provides methods to invoke the method and obtain information about its parameters, return type, and attributes.
  • FieldInfo: Represents a field in C# and provides methods to get and set the value of the field.
  • PropertyInfo: Represents a property in C# and provides methods to get and set the value of the property.
  • EventInfo: Represents an event in C# and provides methods to add and remove event handlers.

Here's an example of how to use reflection to obtain information about a type and its members:

using System;
using System.Reflection;

public class MyClass
{
    public string MyProperty { get; set; }
    public void MyMethod(int param)
    {
        Console.WriteLine($"MyMethod called with parameter {param}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Type type = typeof(MyClass);
        Console.WriteLine($"Type name: {type.Name}");

        PropertyInfo property = type.GetProperty("MyProperty");
        Console.WriteLine($"Property name: {property.Name}");

        MethodInfo method = type.GetMethod("MyMethod");
        Console.WriteLine($"Method name: {method.Name}");
        Console.WriteLine($"Method parameter count: {method.GetParameters().Length}");
    }
}

In this example, we define a simple class MyClass with a property and a method. In the Main method of our console application, we use the typeof operator to obtain the Type object for the MyClass type. We then use the GetProperty and GetMethod methods of the Type class to obtain the PropertyInfo and MethodInfo objects for the MyProperty property and MyMethod method, respectively. Finally, we use the properties of these objects to obtain information about the name and parameter count of the property and method.