When you write a call that would invoke a method that is not accessible (using the standard C# access rules), then the inaccessible method won't be called and the runtime will call the TryInvokeMember
(where you can handle the call in some other way). Here is an example, so that you can try it:
class Test : DynamicObject {
public void Foo() {
Console.WriteLine("Foo called");
}
protected void Bar() {
Console.WriteLine("Bar called");
}
public override bool TryInvokeMember
(InvokeMemberBinder binder, object[] args, out object result) {
Console.WriteLine("Calling: " + binder.Name);
return base.TryInvokeMember(binder, args, out result);
}
}
Now, we can create an instance of the object and try calling some of its methods:
dynamic d = new Test();
d.Foo(); // this will call 'Foo' directly (without calling 'TryInvokeMember')
d.Bar(); // this will call 'TryInvokeMember' and then throw exception
So, if you call the base
implementation of TryInvokeMember
, the C# dynamic binder will fail when calling an inaccessible method, but you can define your own handling of the case in TryInvokeMember
(by setting the result
to some value and returning true
).