Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between TryInvokeMember and TryInvoke

This is part of DynamicObject class:

public class DynamicObject : IDynamicMetaObjectProvider
{ 
    ...
    public virtual bool TryInvoke(InvokeBinder binder, object[] args, out object result)
    {
      result = (object) null;
      return false;
    }
    ...
    public virtual bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
      result = (object) null;
      return false;
    }
}

From MSDN:
TryInvoke: Provides the implementation for operations that invoke an object
TryInvokeMember: Provides the implementation for operations that invoke a member

I want to know the real difference between this two methods because they have almost the same syntax and implementation. I already know that TryInvoke if for objects or delegates, and TryInvokeMember is for methods, but why two methods for this? A good example would be appreciated.

like image 285
Tom Sarduy Avatar asked Oct 28 '12 18:10

Tom Sarduy


2 Answers

The documentation isn't really clear, but the examples for TryInvoke and TryInvokeMember show the difference. TryInvoke is called when invoking the object (that is treating it like a delegate) and TryInvokeMember is used when invoking a method on the object.

The example below is derived from the MSDN samples:

dynamic number;
....
// Invoking an object. 
// The TryInvoke method is called.
number(2, "Two");

// Calling a method
// The TryInvokeMember method is called.
number.Clear();

The implementations you are showing are the same because they are both null implementations. Returning false means that the method that is trying to be called is not implemented.

If there was a non-null implementation the difference would be that TryInvokeMember would examine the binder.Name property to determine which method would be called, while that would not be set for TryInvoke.

like image 193
shf301 Avatar answered Nov 15 '22 09:11

shf301


also

Console.WriteLine(number); // will invoke an object , and the TryInvoke method is called

like image 37
user2162974 Avatar answered Nov 15 '22 10:11

user2162974