Method Parameters

Suppose we want to dynamically call string's Substring method.

Statically, this would be done as follows:


using System;
using System.Reflection;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        Console.WriteLine("java2s.com".Substring(2)); 

    }
}

Here's the dynamic equivalent with reflection:


using System;
using System.Reflection;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        Type type = typeof(string);
        Type[] parameterTypes = { typeof(int) };
        MethodInfo method = type.GetMethod("Substring", parameterTypes);

        object[] arguments = { 2 };
        object returnValue = method.Invoke("java2s.com", arguments); 
        Console.WriteLine(returnValue); 

    }
}

The output:


va2s.com
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.