Click here to Skip to main content
11,576,667 members (57,718 online)
Click here to Skip to main content

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

, 7 Aug 2007 CPOL 144.6K 2.1K 67
Rate this:
Please Sign up or sign in to vote.
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:

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.

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:

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.

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:

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.)

 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:

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)

Share

About the Author

Matt Perdeck
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.

You may also be interested in...

Comments and Discussions

 
GeneralBrilliant Pin
Member 113207582-Apr-15 3:50
memberMember 113207582-Apr-15 3:50 
GeneralGreat just what I was looking for Pin
SteveSumner15-Mar-15 23:21
memberSteveSumner15-Mar-15 23:21 
QuestionThanks Pin
Member 108070799-Feb-15 19:55
memberMember 108070799-Feb-15 19:55 
QuestionDynamically Invoke A Method, Given Strings with Method Name and Class Name (View) Pin
k0718-Feb-14 1:54
memberk0718-Feb-14 1:54 
Questiononly works with Static methods? Pin
Member 889461427-Apr-12 3:14
memberMember 889461427-Apr-12 3:14 
Generalits good Pin
Langa Manish18-Jan-10 18:29
memberLanga Manish18-Jan-10 18:29 
Generalgood article Pin
parthi intel5-Mar-09 0:25
memberparthi intel5-Mar-09 0:25 
QuestionNice article...but what about different parameters with different types? Pin
Member 22902785-Jun-08 18:33
memberMember 22902785-Jun-08 18:33 
AnswerRe: Nice article...but what about different parameters with different types? Pin
dudeserius23-Jun-08 16:12
memberdudeserius23-Jun-08 16:12 
GeneralRe: Nice article...but what about different parameters with different types? Pin
Godwin Sam Josh5-Sep-08 9:30
memberGodwin Sam Josh5-Sep-08 9:30 
GeneralRe: Nice article...but what about different parameters with different types? Pin
dudeserius15-Dec-08 23:07
memberdudeserius15-Dec-08 23:07 
GeneralRe: Nice article...but what about different parameters with different types? Pin
Genesis20019-Apr-10 8:10
memberGenesis20019-Apr-10 8:10 
GeneralRe: Nice article...but what about different parameters with different types? Pin
mdelgert@hotmail.com4-Jun-12 12:11
membermdelgert@hotmail.com4-Jun-12 12:11 
QuestionHowabout dynamic execution of a method in the current class instance? Pin
astanton197819-Mar-08 5:00
memberastanton197819-Mar-08 5:00 
AnswerRe: Howabout dynamic execution of a method in the current class instance? Pin
dudeserius23-Jun-08 15:54
memberdudeserius23-Jun-08 15:54 
GeneralRe: Howabout dynamic execution of a method in the current class instance? Pin
Jayanta Chatterjee14-Jan-13 5:10
memberJayanta Chatterjee14-Jan-13 5:10 
AnswerRe: Howabout dynamic execution of a method in the current class instance? Pin
dudeserius27-Jan-13 8:43
memberdudeserius27-Jan-13 8:43 
GeneralRe: Howabout dynamic execution of a method in the current class instance? Pin
Jayanta Chatterjee27-Jan-13 17:41
memberJayanta Chatterjee27-Jan-13 17:41 
AnswerRe: Howabout dynamic execution of a method in the current class instance? Pin
dudeserius23-Apr-13 8:56
memberdudeserius23-Apr-13 8:56 
GeneralGreat Pin
error140815-Aug-07 10:07
membererror140815-Aug-07 10:07 
GeneralVery cool and useful Pin
Mike DiRenzo7-Aug-07 5:56
memberMike DiRenzo7-Aug-07 5:56 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 7 Aug 2007
Article Copyright 2007 by Matt Perdeck
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid