Does C# know respondsto: or similar?

  • Thread starter Thread starter Philipp Ott
  • Start date Start date
P

Philipp Ott

Hello!

I would like to send a method based on a string to an object.

In Smalltalk, Ruby and Objective-C exists a respondsto: method which allows you to ask an object dynamically if it responds to a certain method and also to invoke the method with some parameters.

Is there such a functionality in C#? I get a string with a methodname and would like to check if an object has the method "amethod:". If so then I would like to send this message to the object and pass some parameters along.

Does this work in C#?

Can I get a runtime-list of methods supported from an object and iterate myself through the list and compare with the string and invoke the method then?

Thank you for any help,
regards
Philipp Ott
 
Philipp Ott said:
I would like to send a method based on a string to an object.

In Smalltalk, Ruby and Objective-C exists a respondsto: method
which allows you to ask an object dynamically if it responds
to a certain method and also to invoke the method with some
parameters.

Is there such a functionality in C#? I get a string with a methodname
and would like to check if an object has the method "amethod:". If
so then I would like to send this message to the object and pass
some parameters along.

Firstly - terminology-wise, people don't tend to talk about "sending
messages" in .NET (or at least, not in this context) - it's more just
invoking or calling methods. Anyway, moving on - yes, you absolutely
can do this, although it's not part of C# itself, it's part of the .NET
framework, and it's called reflection.

First you need to get the Type object related to your instance, which
you do using the GetType() method. You can then call GetMethod() on the
Type, and then calling Invoke() on the MethodInfo returned by
GetMethod. If you look up all of those methods in MSDN you'll get far
more information than I could possibly go into in a post :)

Hope that helps - let me know if you have any problems.
 
Back
Top