0

Is it possible in .NET, to invoke a method/function on an object and get back it's return value without knowing the type of the object?

All the examples I could find so far use reflection and need to know the type of the object to get it's method list to invoke them.

In short, I want to invoke a method of a given name and with given parameters on any object, and get back the return value, in case this method really exists.

For example: Let's say I have a library X.dll with a class Y and a function Z inside it. Function Z takes two string parameters and returns a string. I have another library A.dll, which is NOT referencing X.dll. A.dll has a function B somewhere inside it, which takes an object of type Y as a parameter, but since there's no referencing, this parameter is declared as object. Inside this function B I need to invoke function Z and do something with it's return value.

Nostromo
  • 1,177
  • 10
  • 28
  • 2
    If the method name and signature is known in advance: `dynamic`; otherwise, reflection throughput; `obj.GetType().GetMethod(...)` etc and invoke - should work fine; do you have a dummy example that *isn't* working how you'd expect? – Marc Gravell May 08 '20 at 10:34
  • 1
    No, I'm inside a giant project and just wanted to figure out a way to do some new requirement. If this GetType().GetMethod().Invoke is working without a reference to the other DLL, I'll give it a try. Thank you. – Nostromo May 08 '20 at 10:39

1 Answers1

0

Unfortunately, C# does not support class level generic type inference. There were many occasions which I wished to use reflection with the same purpose you described. It seems the feature's outweghts its costs. There is a throughout discussion about this theme here:

Why can't the C# constructor infer type?

Pedro Coelho
  • 1,411
  • 3
  • 18
  • 31
  • This question isn't about constructing types. Other than constructing types, though, C# does a lot of type inference. Your first sentence is wrong unless you explicitly state you are talking about constructor type inference. – Enigmativity May 09 '20 at 02:30
  • @Enigmativity You are right, I was not specific enough. Now I edited my answer with "Unfortunately, C# does not support class level generic type inference". Thanks. – Pedro Coelho May 09 '20 at 02:57