I have a really weird problem. The below code works fine if I create a new console app and put the code in but if i create a new console app in my solution and paste exactly the same code in I get a runtime binder exception that the dynamic does not contain a definition for hello. The wierd things is in my existing solution the code never goes into TryGetMember().
This is really bugging me and the solution is too big to move into a new solution and I not convinced that will fix it. In the console application that doesn’t work all the reference are the same as in the one that does work. the only difference being it is not in the solution. The whole solution is acting the same way with dynamics – the funny thing is this was working but suddenly stop so i create this simple program to test the theory.
Edit: The application that doesn’t work in the solution works fine if I don’t attach the debugger i.e. Ctrl+F5.
Any ideas?
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary["hello"] = "world";
dynamic d = new MyDynamicModel(dictionary);
var a = d.hello;
}
}
public class MyDynamicModel : DynamicObject
{
private IDictionary<string, object> Values { get; set; }
public MyDynamicModel(IDictionary<string, object> dict)
{
Values = dict;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return Values.TryGetValue(binder.Name, out result);
}
}
}
It sounds like you have visual studio setup to break on thrown exceptions. Just using Dynamics will throw and handle more exceptions then you think when dealing with C# objects including dynamic objects. The C# binder always tries to do things like call the static version first etc, and then throws a RuntimeBindingException that it can’t find the member, handles it, and tries again for the dynamic version.
Under
Debug > Exceptionsmake sure theThrownisn’t checked on RuntimeBinderException or even just all CLR Exceptions.