Axis
Axis

Reputation: 846

C# passing dynamic method as parameter

So I have a dynamic object and I want to execute a method from it but I need the method to be passed in as a parameter. I have found no way to do this and was wondering if anyone here could help.

something like:

public static void RunMethod(methodInTheDynamicObject)
{
    myDynamicObject.methodInTheDynamicObject();
}

Upvotes: 0

Views: 4413

Answers (3)

Axis
Axis

Reputation: 846

I probably should have let you know that my dynamic object was an Iron-Python script. Anyways I figured out.

public static void RunMethod(string script, string method, object[] param)
{
    try
    {
        dynamic dynamicObj = Scripts[script];
        var operations = ironPython.Operations;
        operations.InvokeMember(dynamicObj, method, param);
    }
    catch { }
}

Upvotes: 0

Nadir Muzaffar
Nadir Muzaffar

Reputation: 4842

My preference in this case is usually to define a delegate:

public delegate void MyFunction(string p1, int p2);

public void Foo(MyFunction myFunction) {
    myFunction("something", 2);
}

Or you can use System.Reflection and pass in MethodInfo and use it like so:

public void Foo(MethodInfo methodInfo) {
    methodInfo.Invoke(new object[] {"something", 2});
}

You can find out more about MethodInfo.Invoke here. They have some examples. But again, delegates are probably the cleaner way to go.

Upvotes: 3

Dessus
Dessus

Reputation: 2177

I believe you are wanting to pass in a delegate. See the example here: http://geekswithblogs.net/joycsharp/archive/2008/02/15/simple-c-delegate-sample.aspx

If you needed a hardcore approach for runtime generated methods you could try: http://msdn.microsoft.com/en-us/library/exczf7b9.aspx

Upvotes: 2

Related Questions