0
0
CsharpHow-ToBeginner · 4 min read

How to Use Reflection in C#: Syntax and Examples

In C#, use System.Reflection to inspect types, methods, and properties at runtime. You get a Type object with typeof() or GetType(), then use methods like GetMethods() or Invoke() to work with members dynamically.
📐

Syntax

Reflection in C# uses the System.Reflection namespace. You start by getting a Type object representing a class or object. Then you can access its members like methods, properties, and fields.

  • typeof(ClassName): Gets the Type of a class.
  • object.GetType(): Gets the Type of an instance.
  • Type.GetMethods(): Returns all methods of the type.
  • MethodInfo.Invoke(): Calls a method dynamically.
csharp
using System;
using System.Reflection;

class Example {
    public void SayHello() {
        Console.WriteLine("Hello from reflection!");
    }
}

class Program {
    static void Main() {
        Type type = typeof(Example); // Get type info
        MethodInfo method = type.GetMethod("SayHello"); // Get method info
        object instance = Activator.CreateInstance(type); // Create instance
        method.Invoke(instance, null); // Call method
    }
}
Output
Hello from reflection!
💻

Example

This example shows how to use reflection to find and invoke a method called Greet on a class instance. It demonstrates getting the type, creating an instance, and calling the method dynamically.

csharp
using System;
using System.Reflection;

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

    public void Greet() {
        Console.WriteLine($"Hello, my name is {Name}.");
    }
}

class Program {
    static void Main() {
        Type personType = typeof(Person);
        object personInstance = Activator.CreateInstance(personType);

        // Set property using reflection
        PropertyInfo nameProp = personType.GetProperty("Name");
        nameProp.SetValue(personInstance, "Alice");

        // Get method and invoke
        MethodInfo greetMethod = personType.GetMethod("Greet");
        greetMethod.Invoke(personInstance, null);
    }
}
Output
Hello, my name is Alice.
⚠️

Common Pitfalls

Reflection can be tricky. Common mistakes include:

  • Using wrong method or property names causes null results or exceptions.
  • Not handling exceptions from Invoke(), which can throw if method parameters are wrong.
  • Performance overhead: reflection is slower than direct calls.
  • Forgetting to check for null when a member is not found.

Always validate that the member exists before invoking it.

csharp
using System;
using System.Reflection;

class Program {
    static void Main() {
        Type type = typeof(string);
        MethodInfo method = type.GetMethod("NonExistentMethod");

        // Wrong: no null check
        // method.Invoke(null, null); // This throws NullReferenceException

        // Right: check for null
        if (method != null) {
            method.Invoke(null, null);
        } else {
            Console.WriteLine("Method not found.");
        }
    }
}
Output
Method not found.
📊

Quick Reference

Reflection FeatureUsageDescription
Get Typetypeof(ClassName) or instance.GetType()Get the Type object for a class or instance
Get Methodtype.GetMethod("MethodName")Retrieve a method info by name
Invoke Methodmethod.Invoke(instance, parameters)Call a method dynamically
Get Propertytype.GetProperty("PropertyName")Access a property info
Set Property Valueproperty.SetValue(instance, value)Set a property value dynamically
Create InstanceActivator.CreateInstance(type)Create an object instance at runtime

Key Takeaways

Use System.Reflection to inspect and manipulate types at runtime in C#.
Always get a Type object first using typeof() or GetType() before accessing members.
Check for null when retrieving members to avoid exceptions.
Use MethodInfo.Invoke() to call methods dynamically on instances.
Reflection is powerful but slower than direct calls and should be used carefully.