Question

I need to call a method on an object but I do not know the method name until runtime.

What are the techniques available?

(e.g. GetMethod().Invoke(), delegates, c# 4.0 dynamic)

Thanks!

Was it helpful?

Solution

The C# 4.0 dynamic functionality is going to be the easiest way to do this. In a very real sense, dynamic is "just a wrapper" around Reflection. It's a very good wrapper, though, that is probably your best option.

Other ways, in approximately increasing level of difficult:

  • Using a third-party Reflection library. Not sure what's out there these days.
  • Writing your own Reflection code.
  • Use the CodeDOM to create code that calls the method you want to call.
  • Emit IL that does pretty much the same thing as the CodeDOM generated code.
  • Create C# source code that you then compile into an assembly that you can call, which in turn calls the desired method.

The last three are not for the faint of heart. Your best bet is to use dynamic or write your own Reflection code. If I had had dynamic three years ago when I was writing code for something similar, I would have used it.

OTHER TIPS

You can use Reflection to call functions that you do not know the name of until run time. Here's some doc:

http://msdn.microsoft.com/en-us/library/f7ykdhsy%28VS.80%29.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top