O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.12. Dynamically Invoking Members

Problem

You have a list of method names that you wish to invoke dynamically within your application. As your code executes, it will pull names off of this list and attempt to invoke these methods. This technique would be useful to create a test harness for components that read in the methods to execute from an XML file and execute them with the given parameters.

Solution

The TestDynamicInvocation method opens the XML configuration file, reads out the test information, and executes each test method dynamically:

public static void TestDynamicInvocation( )
{
    // read in the methods to run from the xml file
    XmlDocument doc = new XmlDocument( );
    doc.Load(@"C:\C#Cookbook\SampleClassLibraryTests.xml");

    // get the tests to run
    XmlNodeList nodes = doc.SelectNodes(@"Tests/Test");

    // run each test method
    foreach(XmlNode node in nodes)
    {
        object obj = DynamicInvoke(node,
                                   @"C:\C#Cookbook\SampleClassLibrary.dll");

        // print out the return
        Console.WriteLine("\tReturned object: " + obj);
        Console.WriteLine("\tReturned object: " + obj.GetType( ).FullName);
    }
}

The XML document in which the test method information is contained looks like this:

<?xml version="1.0" encoding="utf-8" ?> <Tests> <Test className='SampleClassLibrary.SampleClass' methodName='TestMethod1'> <Parameter>Running TestMethod1</Parameter> </Test> <Test className='SampleClassLibrary.SampleClass' methodName='TestMethod2'> <Parameter>Running TestMethod2</Parameter> <Parameter>27</Parameter> </Test> </Tests> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required