Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute method on dynamic

I am sure this question has been answered somewhere but I'm having major problems finding the right combination of keywords to find it.

I am curious to know if its possible to do something like this:

dynamic someObj = new SomeObject();

var methodName = "someMethodName";

// execute methodName on someObj

I basically want to know if its possible to execute a method on a dynamic object using a variable that stores the methods name.

like image 897
devshorts Avatar asked Jun 14 '12 22:06

devshorts


2 Answers

You can do it on any object, not necessarily a dynamic one using reflection.

object obj = new SomeObject();
var meth = obj.GetType().GetMethod("someMethodName");
meth.Invoke(obj, new object[0]); // assuming a no-arg method

When you use dynamic, you can use any identifier for a method name, and the compiler will not complain:

dynamic obj = MakeSomeObject();
obj.someMethodName(); // Compiler takes it fine, even if MakeSomeObject returns an object that does not declare someMethodName()
like image 107
Sergey Kalinichenko Avatar answered Sep 19 '22 11:09

Sergey Kalinichenko


Well, you actually don't need "someMethodName" in quotes. You just do this (full program listing):

class Program
{
    static void Main(string[] args)
    {
        dynamic obj = new SomeObject();
        obj.someMethodName("hello");
    }
}

public class SomeObject
{
    public void someMethodName(string message)
    {
        Console.WriteLine(message);
    }
}

In case your method name comes from some evil place like javascript or something, then you can do this:

class Program
{
    static void Main(string[] args)
    {
        dynamic obj = new SomeObject();
        var meth = obj.GetType().GetMethod("someMethodName");
        meth.Invoke(obj, new object[1]{"hello"});
    }
}

public class SomeObject
{
    public void someMethodName(string message)
    {
        Console.WriteLine(message);
    }
}
like image 40
Milimetric Avatar answered Sep 21 '22 11:09

Milimetric