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.
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()
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With