Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17481

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.

Upvotes: 17

Views: 2416

Answers (2)

shf301
shf301

Reputation: 31404

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.

Upvotes: 16

user2162974
user2162974

Reputation: 11

also

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

Upvotes: 1

Related Questions