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.
Reflection allows you to:
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);
}
MethodInfo method = type.GetMethod("SayHello");
method.Invoke(personInstance, null);
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 });
FieldInfo field = typeof(User).GetField("password", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(userInstance, "newPassword");
ConstructorInfo ctor = typeof(Person).GetConstructor(new[] { typeof(string) });
object obj = ctor.Invoke(new object[] { "Aslyne" });
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!