06 Feb 2024




Intermediate

To implement reflection in C#, you typically use classes and methods provided by the System.Reflection namespace. Here are some common tasks and examples of how to use reflection:

  1. Retrieve Type Information:

    • To get information about a type, you can use the Type class.
    Type myType = typeof(MyClass);
    Console.WriteLine($"Type Name: {myType.Name}, Namespace: {myType.Namespace}");
    
  2. Inspect Members:

    • To inspect members of a type, you can use methods like GetProperties, GetMethods, GetFields, etc.
    foreach (var property in myType.GetProperties())
    {
        Console.WriteLine($"Property: {property.Name}, Type: {property.PropertyType}");
    }
    
  3. Invoke Methods Dynamically:

    • To invoke a method dynamically, you can use the Invoke method.
    object instance = Activator.CreateInstance(myType);
    MethodInfo myMethod = myType.GetMethod("MyMethod");
    myMethod.Invoke(instance, null);
    
  4. Create Instances Dynamically:

    • To create an instance of a type dynamically, you can use the Activator.CreateInstance method.
    object instance = Activator.CreateInstance(myType);
    
  5. Work with Attributes:

    • To work with custom attributes, you can use the GetCustomAttributes method.
    var attributes = myType.GetCustomAttributes(typeof(MyAttribute), true);
    foreach (var attribute in attributes)
    {
        Console.WriteLine($"Attribute: {attribute}");
    }
    

Here's a more complete example that demonstrates several aspects of reflection:

using System;
using System.Reflection;

public class MyClass
{
    public string MyProperty { get; set; }

    public void MyMethod()
    {
        Console.WriteLine("Executing MyMethod");
    }
}

class Program
{
    static void Main()
    {
        Type myType = typeof(MyClass);

        // Retrieve type information
        Console.WriteLine($"Type Name: {myType.Name}, Namespace: {myType.Namespace}");

        // Inspect properties
        foreach (var property in myType.GetProperties())
        {
            Console.WriteLine($"Property: {property.Name}, Type: {property.PropertyType}");
        }

        // Create an instance and invoke a method
        object instance = Activator.CreateInstance(myType);
        MethodInfo myMethod = myType.GetMethod("MyMethod");
        myMethod.Invoke(instance, null);
    }
}

This example covers basic reflection tasks, but keep in mind that reflection has performance implications and should be used carefully. Additionally, error handling is crucial when working with reflection to handle potential exceptions that may occur at runtime.

c-sharp
reflection