Click here to Skip to main content
15,881,588 members
Articles / Web Development / ASP.NET
Article

Dynamically Invoke A Method, Given Strings with Method Name and Class Name

Rate me:
Please Sign up or sign in to vote.
4.77/5 (23 votes)
7 Aug 2007CPOL3 min read 285.2K   3.3K   69   22
Sometimes you need to compute the name of a method into a string. This article shows how to call a method given a string with the method's name and class.

Introduction

I recently needed to write some code that would compute the name of a method into a string, and then call that method as shown below:

C#
string s1 = "The";
string s2 = "Method";
string methodName = s1 + s2; // methodName now holds "TheMethod"
    
... code that somehow calls the method whose name is in variable methodName
... in this case, the method TheMethod

Like so many things in .NET, this turned out to be easy - as long as you know how to do it.

Simple Solution

Below is the code that will do the trick, wrapped in the method InvokeStringMethod. As you see, it takes only two lines to call another method given its name as a string, and its class name also as a string. Read the comments in the code to see how it works.

C#
public static string InvokeStringMethod(string typeName, string methodName)
{
    // Get the Type for the class
    Type calledType = Type.GetType(typeName);

    // Invoke the method itself. The string returned by the method winds up in s
    String s = (String)calledType.InvokeMember(
                    methodName,
                    BindingFlags.InvokeMethod | BindingFlags.Public | 
                        BindingFlags.Static,
                    null,
                    null,
                    null);

    // Return the string that was returned by the called method.
    return s;
}  

This method assumes that the called method has no parameters and returns a string. Pass the name of the method in parameter methodName, and the name of its class in typeName. For example:

C#
string s = string InvokeStringMethod("TheClass", "TheMethod");

Pass a Parameter to the Called Method

Below is a version that calls a method that expects one parameter of type string.

Have a look at the code. Passing parameters to the called function is simply a matter of passing them to InvokeMember as an array of Objects. InvokeMember in turn passes those objects on as parameters to the called method.

C#
public static string InvokeStringMethod2
    (string typeName, string methodName, string stringParam)
{
    // Get the Type for the class
    Type calledType = Type.GetType(typeName);

    // Invoke the method itself. The string returned by the method winds up in s.
    // Note that stringParam is passed via the last parameter of InvokeMember,
    // as an array of Objects.
    String s = (String)calledType.InvokeMember(
                    methodName,
                    BindingFlags.InvokeMethod | BindingFlags.Public | 
                        BindingFlags.Static,
                    null,
                    null,
                    new Object[] { stringParam });

    // Return the string that was returned by the called method.
    return s;
}

When you call this version, pass a string in parameter stringParam. InvokeStringMethod2 will pass that string on to the called method. For example:

C#
string s = string InvokeStringMethod2("TheClass", "TheMethod", "The string to pass on");

Call a Method in Another Project and Namespace

You may have organised your code into several projects and namespaces. The version below calls a method that may sit in a different project and/or namespace than the caller. (This version assumes that the called method doesn't take parameters.)

C#
 public static string InvokeStringMethod3(
                        string assemblyName,
                        string namespaceName,
                        string typeName,
                        string methodName)
{
    // Get the Type for the class
    Type calledType = Type.GetType(namespaceName + "." + typeName + "," + assemblyName);

    // Invoke the method itself. The string returned by the method winds up in s
    String s = (String)calledType.InvokeMember(
                    methodName,
                    BindingFlags.InvokeMethod | BindingFlags.Public | 
                        BindingFlags.Static,
                    null,
                    null,
                    null);

    // Return the string that was returned by the called method.
    return s;
}

It assumes that each project gets compiled into its own assembly, with project and assembly having the same name. This is normally the case.

Be sure to add a reference in the project that makes the call to the project that contains the called method! Otherwise, the code can't find the assembly.

When you call this version, pass in the name of the project and the namespace as well as the class name and method name. Like so:

C#
string s = string InvokeStringMethod3
            ("TheProject", "TheNamespace", "TheClass", "TheMethod");

Learn More

When looking at the code above, you will have found that calling a method given a string with its name takes two steps:

  1. Call method GetType of class Type, to get the Type corresponding to the class that contains the method.
  2. Call method InvokeMember on the type, to actually call the method.

To learn more, search MSDN for Type.GetType, and InvokeMember.

Some of the more interesting options include calling private methods rather than public ones, and picking a particular overloaded method.

Have a Play

To experiment a bit more, get the download that comes with this article. It has a tiny Web site serving as a test bed.

The most important files in the download are listed below:

  • DynamicallyInvokeMethodGivenItsNameAsAString.sln - Double click this file to open the solution in Visual Studio
  • Default.aspx.cs - Calls the three versions shown above
  • App_Code/TypeUtils.cs - The class holding the three versions
  • App_Code/TestClass, App_Code/TestClass2 - Classes with methods to call
  • TestClass3 in project TestProject - A class in a separate project, with a different namespace

History

  • 7th August, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Australia Australia
Twitter: @MattPerdeck
LinkedIn: au.linkedin.com/in/mattperdeck
Current project: JSNLog JavaScript Logging Package

Matt has over 9 years .NET and SQL Server development experience. Before getting into .Net, he worked on a number of systems, ranging from the largest ATM network in The Netherlands to embedded software in advanced Wide Area Networks and the largest ticketing web site in Australia. He has lived and worked in Australia, The Netherlands, Slovakia and Thailand.

He is the author of the book ASP.NET Performance Secrets (www.amazon.com/ASP-NET-Site-Performance-Secrets-Perdeck/dp/1849690685) in which he shows in clear and practical terms how to quickly find the biggest bottlenecks holding back the performance of your web site, and how to then remove those bottlenecks. The book deals with all environments affecting a web site - the web server, the database server and the browser.

Matt currently lives in Sydney, Australia. He recently worked at Readify and the global professional services company PwC. He now works at SP Health, a global provider of weight loss web sites such at CSIRO's TotalWellBeingDiet.com and BiggestLoserClub.com.

Comments and Discussions

 
QuestionGreat ! Pin
igetorix15-Sep-17 3:02
igetorix15-Sep-17 3:02 
GeneralBrilliant Pin
Member 113207582-Apr-15 3:50
Member 113207582-Apr-15 3:50 
GeneralGreat just what I was looking for Pin
SteveSumner15-Mar-15 23:21
SteveSumner15-Mar-15 23:21 
QuestionThanks Pin
Ajokar-108070799-Feb-15 19:55
Ajokar-108070799-Feb-15 19:55 
QuestionDynamically Invoke A Method, Given Strings with Method Name and Class Name (View) Pin
k0718-Feb-14 1:54
k0718-Feb-14 1:54 
Questiononly works with Static methods? Pin
Member 889461427-Apr-12 3:14
Member 889461427-Apr-12 3:14 
Generalits good Pin
Manish Langa18-Jan-10 18:29
Manish Langa18-Jan-10 18:29 
Generalgood article Pin
parthi intel5-Mar-09 0:25
parthi intel5-Mar-09 0:25 
QuestionNice article...but what about different parameters with different types? Pin
Member 22902785-Jun-08 18:33
Member 22902785-Jun-08 18:33 
AnswerRe: Nice article...but what about different parameters with different types? Pin
dudeserius23-Jun-08 16:12
dudeserius23-Jun-08 16:12 
GeneralRe: Nice article...but what about different parameters with different types? Pin
Josh1991185-Sep-08 9:30
Josh1991185-Sep-08 9:30 
GeneralRe: Nice article...but what about different parameters with different types? Pin
dudeserius15-Dec-08 23:07
dudeserius15-Dec-08 23:07 
GeneralRe: Nice article...but what about different parameters with different types? Pin
Genesis20019-Apr-10 8:10
Genesis20019-Apr-10 8:10 
GeneralRe: Nice article...but what about different parameters with different types? Pin
mdelgert@hotmail.com4-Jun-12 12:11
mdelgert@hotmail.com4-Jun-12 12:11 
QuestionHowabout dynamic execution of a method in the current class instance? Pin
astanton197819-Mar-08 5:00
astanton197819-Mar-08 5:00 
AnswerRe: Howabout dynamic execution of a method in the current class instance? Pin
dudeserius23-Jun-08 15:54
dudeserius23-Jun-08 15:54 
GeneralRe: Howabout dynamic execution of a method in the current class instance? Pin
JayantaChatterjee14-Jan-13 5:10
professionalJayantaChatterjee14-Jan-13 5:10 
AnswerRe: Howabout dynamic execution of a method in the current class instance? Pin
dudeserius27-Jan-13 8:43
dudeserius27-Jan-13 8:43 
GeneralRe: Howabout dynamic execution of a method in the current class instance? Pin
JayantaChatterjee27-Jan-13 17:41
professionalJayantaChatterjee27-Jan-13 17:41 
AnswerRe: Howabout dynamic execution of a method in the current class instance? Pin
dudeserius23-Apr-13 8:56
dudeserius23-Apr-13 8:56 
I ran your code through LinqPad, and it seems I deduced the problem. Your binding flags needs to also include instance methods

C#
this.GetType().InvokeMember(textBox1.Text, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, this, null);


That should do the trick for you. I apologize for just now responding. I've been away from the internet for a while.
----------------------------
Nathan VanBuskirk
C#, VB.NET, C++, Java Developer
http://Seriussoft.com

GeneralGreat Pin
error140815-Aug-07 10:07
error140815-Aug-07 10:07 
GeneralVery cool and useful Pin
Mike DiRenzo7-Aug-07 5:56
Mike DiRenzo7-Aug-07 5:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.