Call a method using reflection

Location: BlogsRainer's Blog   
Posted by: Rainer Stropek2008-02-01 16:37:33Z

I have been asked how you can call a method given its name in a string variable using reflection. Here is a code sample showing how to do it.

using System;
using System.Reflection;
namespace CallMethodByNameWithReflection
{
    class MyClass
    {
        public void SayHello()
        {
            Console.WriteLine("Hello World!");
        }
    }
    class Program
    {
        public static void CallMethod(object o, string MethodName)
        {
            var t = o.GetType();
            var mi = t.GetMethod(MethodName);
            mi.Invoke(o, null);
        }
        static void Main(string[] args)
        {
            var c = new MyClass();
            CallMethod(c, "SayHello");
        }
    }
}

Permalink | Trackback

Your name:
Title:
Comment:
Add Comment  Cancel 

Search Blog

Blog List

Blog Archive