MSDN Documentation

System.Reflection.Type Examples

Explore practical examples of using the System.Reflection.Type class to inspect and manipulate types at runtime in the .NET framework.

1. Getting a Type Object

Demonstrates various ways to obtain a Type object for a given class.


using System;

public class Example
{
    public static void Main(string[] args)
    {
        // Method 1: Using typeof() operator
        Type type1 = typeof(string);
        Console.WriteLine($"Type 1: {type1.FullName}");

        // Method 2: Using GetType() method on an instance
        string instance = "Hello Reflection";
        Type type2 = instance.GetType();
        Console.WriteLine($"Type 2: {type2.FullName}");

        // Method 3: Using Type.GetType() with assembly-qualified name
        // (Requires full assembly name if not in the current assembly)
        try
        {
            Type type3 = Type.GetType("System.Int32, mscorlib");
            Console.WriteLine($"Type 3: {type3.FullName}");
        }
        catch (TypeLoadException ex)
        {
            Console.WriteLine($"Error loading type: {ex.Message}");
        }
    }
}
                    

2. Inspecting Type Members

Shows how to retrieve information about fields, properties, methods, and constructors of a type.


using System;
using System.Reflection;

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

    public MyClass(int field, string prop)
    {
        MyField = field;
        MyProperty = prop;
    }

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

public class Example
{
    public static void Main(string[] args)
    {
        Type myType = typeof(MyClass);

        Console.WriteLine($"--- Inspecting Type: {myType.FullName} ---");

        // Fields
        Console.WriteLine("\nFields:");
        FieldInfo[] fields = myType.GetFields();
        foreach (var field in fields)
        {
            Console.WriteLine($"- {field.FieldType.Name} {field.Name}");
        }

        // Properties
        Console.WriteLine("\nProperties:");
        PropertyInfo[] properties = myType.GetProperties();
        foreach (var prop in properties)
        {
            Console.WriteLine($"- {prop.PropertyType.Name} {prop.Name}");
        }

        // Methods
        Console.WriteLine("\nMethods:");
        MethodInfo[] methods = myType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
        foreach (var method in methods)
        {
            Console.WriteLine($"- {method.ReturnType.Name} {method.Name}()");
        }

        // Constructors
        Console.WriteLine("\nConstructors:");
        ConstructorInfo[] constructors = myType.GetConstructors();
        foreach (var ctor in constructors)
        {
            Console.WriteLine($"- {myType.Name}({string.Join(", ", ctor.GetParameters().Select(p => p.ParameterType.Name))})");
        }
    }
}
                    

3. Invoking Methods Dynamically

Illustrates how to create an instance of a type and call its methods using reflection.


using System;
using System.Reflection;

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public void DisplayMessage(string message)
    {
        Console.WriteLine($"Message: {message}");
    }
}

public class Example
{
    public static void Main(string[] args)
    {
        Type calculatorType = typeof(Calculator);

        // Create an instance of Calculator
        object calculatorInstance = Activator.CreateInstance(calculatorType);

        // Invoke the Add method
        MethodInfo addMethod = calculatorType.GetMethod("Add");
        object result = addMethod.Invoke(calculatorInstance, new object[] { 5, 10 });
        Console.WriteLine($"Result of Add: {result}");

        // Invoke the DisplayMessage method
        MethodInfo displayMethod = calculatorType.GetMethod("DisplayMessage");
        displayMethod.Invoke(calculatorInstance, new object[] { "Hello from dynamic invocation!" });
    }
}
                    

4. Checking Type Attributes and Interfaces

How to determine if a type has specific attributes or implements certain interfaces.


using System;
using System.Collections.Generic;
using System.Reflection;

// Define a custom attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ObsoleteInfoAttribute : Attribute
{
    public string Message { get; }
    public ObsoleteInfoAttribute(string message)
    {
        Message = message;
    }
}

[ObsoleteInfo("This class is no longer recommended.")]
public class OldService { }
public interface IService { }
public class MyService : IService { }

public class Example
{
    public static void Main(string[] args)
    {
        Type oldServiceType = typeof(OldService);
        Type myServiceType = typeof(MyService);

        // Check for attributes
        var obsoleteAttribute = oldServiceType.GetCustomAttribute();
        if (obsoleteAttribute != null)
        {
            Console.WriteLine($"OldService has ObsoleteInfo attribute: {obsoleteAttribute.Message}");
        }

        // Check for interfaces
        bool implementsIService = myServiceType.GetInterfaces().Contains(typeof(IService));
        Console.WriteLine($"MyService implements IService: {implementsIService}");

        bool oldServiceImplementsIService = oldServiceType.GetInterfaces().Contains(typeof(IService));
        Console.WriteLine($"OldService implements IService: {oldServiceImplementsIService}");
    }
}