Doug Finke
Doug Finke

Reputation: 6823

dynamic in C# 4.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()
    {
    }
}

Upvotes: 0

Views: 198

Answers (1)

Andre Vianna
Andre Vianna

Reputation: 1732

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);
}

Upvotes: 3

Related Questions