Reflection in C# is a powerful feature that allows us to inspect and manipulate metadata information of types, members, and other elements in our code at runtime. This gives us the ability to dynamically load assemblies, create objects, invoke methods, access properties, and much more.
One common use case of reflection is when we want to create objects of a certain type without knowing the exact type at compile time. We can use reflection to get the type information dynamically and then instantiate the object. Here is an example of how we can create an object using reflection in C#:
using System;
using System.Reflection;
public class Program
{
public static void Main()
{
// Get the type information of the MyClass class
Type myClassType = Type.GetType("MyNamespace.MyClass");
// Create an instance of the MyClass class
object myClassInstance = Activator.CreateInstance(myClassType);
// Call a method on the instance
myClassType.GetMethod("MyMethod").Invoke(myClassInstance, null);
}
}
public class MyClass
{
public void MyMethod()
{
Console.WriteLine("Hello from MyClass!");
}
}
In this example, we first get the type information of the MyClass
class using Type.GetType()
. Then, we create an instance of the MyClass
class using Activator.CreateInstance()
. Finally, we call the MyMethod
method on the instance using reflection.
Reflection is a powerful feature that should be used carefully, as it can lead to decreased performance and potentially introduce security vulnerabilities. However, when used correctly, it can be a valuable tool for building dynamic and flexible applications in C#.
Top comments (0)