Consider the following:
using System; using System.Dynamic; using System.Linq; namespace DynamicObjectTest { class Program { static void Main(string[] args) { dynamic dyn = new TestDynamic(); Console.ReadKey(); foreach (var i in Enumerable.Range(0, 100)) { Console.WriteLine(dyn.Foo()); Console.WriteLine(dyn.Bar()); } Console.ReadKey(); } } class TestDynamic : DynamicObject { public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (binder.Name == "Foo") { result = "Bar"; return true; } else if (binder.Name == "Bar") { result = "Foo"; return true; } return base.TryInvokeMember(binder, args, out result); } } }
When this program starts, four exceptions of the RuntimeBinderException type are RuntimeBinderException . You can observe this either by hacking all excepted exceptions (Debugging / Exceptions ... / check the box next to “Exclude Common Language Rutime exceptions”) or using perfmon:

Now these exceptions are obviously caught and handled internally, because after that the TryInvokeMember method TryInvokeMember called. However, it seems cruel and misuse of exceptions if you subscribe to the mantra “use exceptions only in exceptional circumstances”. For my specific example, this is not a problem, because the same element is repeatedly called - Foo and Bar . However, I have other scenarios in which members are much less static.
Is there anything that can be done to help runtime call TryInvokeMember without any exceptions?
source share