Search code examples
c#reflection

Replace Method Name Dynamically


I have a method, GetData(), which I would like to exchange its name dynamically based on a string parameter.

The first thing was to Get the Method out of the string parameter, MethodName.

var methodinfo = repository.GetType().GetMethod("MethodName");

Now, how to replace the GetData() method below with the dynamic value that is extracted in methodinfo?

var argumentType = repository.GetData().GetType().GetGenericArguments()[0];

I tried something like this but didn't work:

var argumentType =  methodinfo.GetType().GetGenericArguments()[0];

Solution

  • If I understand your question right you would need something like this:

    public class ProgChoice
    {
        public static void ProgSelection()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
    
            Type t = assembly.GetType("ProgChoice.ProgSelection", false, true);
    
            string lcProgStr = "Prog";
            int liProgNumb = 4;
    
            // Concatenate the 2 strings
            lcProgStr = lcProgStr + liProgNumb.ToString();
    
            MethodInfo method = t.GetMethod(lcProgStr);
            method.Invoke(null, null);
    
            Console.ReadKey();
        }
    }