In C# 4.0, there is a new DynamicObject.
It provides a “magic method” TryInvokeMember() that gets called when trying to call a method that does not exist.
What I would like to know is if TryInvokeMember() gets called when trying to call a protected method from outside the defining class.
I am contrasting the behaviour with PHP, which does call its equivalent “magic method” __call() in this situation.
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:Now, we can create an instance of the object and try calling some of its methods:
So, if you call the
baseimplementation ofTryInvokeMember, the C# dynamic binder will fail when calling an inaccessible method, but you can define your own handling of the case inTryInvokeMember(by setting theresultto some value and returningtrue).