What is Reflection in C#: Explanation and Example
reflection is a way for a program to look at its own structure, like classes and methods, while it is running. It lets you get information about types and even create or use objects dynamically without knowing them at compile time.How It Works
Reflection in C# works like a mirror that lets your program see details about itself while it runs. Imagine you have a toolbox but you don’t know what tools are inside until you open it and look. Reflection lets you open that toolbox (your program) and check what classes, methods, or properties it has.
It uses special classes in the System.Reflection namespace to explore types and members. This means you can find out what methods a class has, what parameters they take, or even create new objects and call methods without writing their names directly in your code.
This is powerful because it adds flexibility, like being able to work with unknown types or plugins added later without changing your original program.
Example
This example shows how to use reflection to get the name of a class and list its methods.
using System; using System.Reflection; public class Person { public string Name { get; set; } public void SayHello() => Console.WriteLine($"Hello, my name is {Name}."); } class Program { static void Main() { Type personType = typeof(Person); Console.WriteLine($"Class Name: {personType.Name}"); MethodInfo[] methods = personType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); Console.WriteLine("Methods:"); foreach (var method in methods) { Console.WriteLine(method.Name); } } }
When to Use
Reflection is useful when you need to work with types or objects that you don’t know about until your program runs. For example:
- Loading plugins or modules dynamically without recompiling your app.
- Inspecting attributes or metadata on classes to change behavior.
- Creating tools like serializers that convert objects to text or back.
- Debugging or testing frameworks that need to explore code structure.
However, reflection can be slower and harder to maintain, so use it only when necessary.
Key Points
- Reflection lets a program examine and use its own structure at runtime.
- It uses classes from
System.Reflectionto get info about types, methods, and properties. - You can create objects and call methods dynamically with reflection.
- It is helpful for plugins, serialization, and dynamic behavior.
- Reflection can impact performance and should be used carefully.