Mastering .NET Reflection in C# - With Real Examples

Mastering .NET Reflection in C# - With Real Examples

Reflection in .NET is a powerful feature that allows you to inspect and manipulate the structure of assemblies, types, properties, methods, and more at runtime. This blog explores practical examples of how to use reflection in C# to dynamically invoke methods, access private members, and call constructors.

What is .NET Reflection?

Reflection allows you to:

  • Inspect assemblies, classes, properties, and methods at runtime
  • Invoke methods dynamically
  • Access private members for testing or special use cases
  • Dynamically create objects

Example: Inspecting a Class

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void SayHello()
    {
        Console.WriteLine("Hello!");
    }
}
Type type = typeof(Person);

foreach (PropertyInfo prop in type.GetProperties())
{
    Console.WriteLine($"{prop.Name} ({prop.PropertyType.Name})");
}

foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
    Console.WriteLine(method.Name);
}

Invoke a Method Dynamically

MethodInfo method = type.GetMethod("SayHello");
method.Invoke(personInstance, null);

Invoke a Method with Parameters

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

MethodInfo method = typeof(Calculator).GetMethod("Add");
object result = method.Invoke(new Calculator(), new object[] { 5, 7 });

Access Private Members

FieldInfo field = typeof(User).GetField("password", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(userInstance, "newPassword");

Invoke Constructors

ConstructorInfo ctor = typeof(Person).GetConstructor(new[] { typeof(string) });
object obj = ctor.Invoke(new object[] { "Aslyne" });

Learn with Me - 1-on-1 Coding Classes

Want to master topics like Reflection and more in C# and .NET? I offer 1-on-1 personalized programming classes for all levels. Whether you're just getting started or preparing for job interviews, I’ll guide you step-by-step.

Contact Me:
Website: https://supernovaservices.com/
WhatsApp: +91-9331897923

Happy Coding!

Any Query / Enrollment Request



Google Review Testimonials

.NET Online Training
Average Rating: 4.9
Votes: 50
Reviews: 50