0

In PowerShell I can set a variable to a string and then use it on a hash table lookup:

$h = @{a=1}
$p = "a"

$h.$p

How can this be done in C# 4.0 with method calls? The following fails because target is not resolved to 'MethodToCall'.

class Program
{
    static void Main(string[] args)
    {
        string target = "MethodToCall";
        dynamic d = new test();
        d.target();
    }
}

class test
{
    public void MethodToCall()
    {
    }
}
3
  • 1
    That's not what "dynamic" lets you do. C# is different from PowerShell here. Commented Jul 13, 2010 at 1:12
  • Remember that C# is not a scripting language. Commented Jul 13, 2010 at 1:16
  • Yes, I know. I realize I am trying to make it one :) Commented Jul 21, 2010 at 14:16

1 Answer 1

3

Dynamic is not the solution. You migth need to use reflection.

static void Main(string[] args)
{
    string target = "MethodToCall";
    var d = new test();
    typeof(test).InvokeMember(target, BindingFlags.InvokeMethod, null, d, null);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.