C# Reflection: How to get class reference from string?

rutger picture rutger · Jun 25, 2009 · Viewed 149.6k times · Source

I want to do this in C#, but I don't know how:

I have a string with a class name -e.g: FooClass and I want to invoke a (static) method on this class:

FooClass.MyMethod();

Obviously, I need to find a reference to the class via reflection, but how?

Answer

Andrew Hare picture Andrew Hare · Jun 25, 2009

You will want to use the Type.GetType method.

Here is a very simple example:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Foo");
        MethodInfo method 
             = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);

        method.Invoke(null, null);
    }
}

class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

I say simple because it is very easy to find a type this way that is internal to the same assembly. Please see Jon's answer for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.