Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Reflection in .NET

Introduction to Reflection

Reflection in .NET allows you to inspect and manipulate metadata of types (classes, interfaces, structs), methods, properties, and more at runtime.

Using Reflection

To use Reflection, you typically work with classes from the System.Reflection namespace such as Assembly, Type, and MethodInfo.

Example: Using Reflection to Get Type Information


using System;
using System.Reflection;

public class Program {
    public static void Main() {
        Type type = typeof(string);
        Console.WriteLine($"Type Name: {type.FullName}");
        Console.WriteLine($"Assembly: {type.Assembly.FullName}");
        Console.WriteLine($"Is Class? {type.IsClass}");
        Console.WriteLine($"Methods:");
        foreach (MethodInfo method in type.GetMethods()) {
            Console.WriteLine($" - {method.Name}");
        }
    }
}
    

Accessing Members Dynamically

Reflection allows you to dynamically access and invoke methods, properties, and constructors of types.

Example: Accessing Members Dynamically


using System;
using System.Reflection;

public class Program {
    public static void Main() {
        Type type = typeof(Math);
        MethodInfo method = type.GetMethod("Pow", new Type[] { typeof(double), typeof(double) });
        object result = method.Invoke(null, new object[] { 2.0, 3.0 });
        Console.WriteLine($"Result of Math.Pow(2, 3): {result}");
    }
}
    

Modifying Objects at Runtime

Reflection allows you to dynamically create instances of types, set property values, and invoke methods.

Example: Modifying Objects at Runtime


using System;
using System.Reflection;

public class Program {
    public static void Main() {
        Type type = typeof(Person);
        object instance = Activator.CreateInstance(type);
        
        PropertyInfo property = type.GetProperty("Name");
        property.SetValue(instance, "John Doe");

        MethodInfo method = type.GetMethod("SayHello");
        method.Invoke(instance, null);
    }
    
    public class Person {
        public string Name { get; set; }

        public void SayHello() {
            Console.WriteLine($"Hello, {Name}!");
        }
    }
}
    

Reflection and Security

Reflection can bypass access modifiers like private and execute code that might otherwise be restricted, so it should be used cautiously in security-sensitive scenarios.

Conclusion

Reflection in .NET is a powerful feature that enables dynamic inspection and manipulation of types and members at runtime, providing flexibility in application development but requiring careful handling in terms of performance and security.