Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 7 Aug 2007
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
Web Developer
Australia Australia
Twitter: @MattPerdeck
Blog: mattperdeck.com
Current project: JSNLog JavaScript Logging Package
 
Matt has over 6 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 recently wrote a book, ASP.NET Performance Secrets (www.packtpub.com/asp-net-site-performance-secrets/book) 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. After 2 years at Readify, he now works at the global professional services company PwC. His current contract ends at 29 June 2014.
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionDynamically Invoke A Method, Given Strings with Method Name and Class Name (View) Pinmemberk0718-Feb-14 1:54 
Questiononly works with Static methods? PinmemberMember 889461427-Apr-12 3:14 
Generalits good PinmemberLanga Manish18-Jan-10 18:29 
Generalgood article Pinmemberparthi intel5-Mar-09 0:25 
QuestionNice article...but what about different parameters with different types? PinmemberMember 22902785-Jun-08 18:33 
AnswerRe: Nice article...but what about different parameters with different types? Pinmemberdudeserius23-Jun-08 16:12 
GeneralRe: Nice article...but what about different parameters with different types? PinmemberGodwin Sam Josh5-Sep-08 9:30 
GeneralRe: Nice article...but what about different parameters with different types? Pinmemberdudeserius15-Dec-08 23:07 
GeneralRe: Nice article...but what about different parameters with different types? PinmemberGenesis20019-Apr-10 8:10 
GeneralRe: Nice article...but what about different parameters with different types? Pinmembermdelgert@hotmail.com4-Jun-12 12:11 
QuestionHowabout dynamic execution of a method in the current class instance? Pinmemberastanton197819-Mar-08 5:00 
AnswerRe: Howabout dynamic execution of a method in the current class instance? Pinmemberdudeserius23-Jun-08 15:54 
GeneralRe: Howabout dynamic execution of a method in the current class instance? PinmemberJayanta Chatterjee14-Jan-13 5:10 
AnswerRe: Howabout dynamic execution of a method in the current class instance? Pinmemberdudeserius27-Jan-13 8:43 
GeneralRe: Howabout dynamic execution of a method in the current class instance? PinmemberJayanta Chatterjee27-Jan-13 17:41 
AnswerRe: Howabout dynamic execution of a method in the current class instance? Pinmemberdudeserius23-Apr-13 8:56 
GeneralGreat Pinmembererror140815-Aug-07 10:07 
GeneralVery cool and useful PinmemberMike 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 | Mobile
Web01 | 2.8.140916.1 | Last Updated 7 Aug 2007
Article Copyright 2007 by Matt Perdeck
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid