Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net DynamicObject implementation that returns null for missing properties rather than a RunTimeBinderException

Tags:

I'd like to be able to do something like the following:

dynamic a = new ExpandoObject(); Console.WriteLine(a.SomeProperty ?? "No such member"); 

but that throws

RunTimeBinderException: 'System.Dynamic.ExpandoObject' does not contain a definition for 'Throw' 

Do you know of an implementation of DynamicObject that would return null for missing definitions, or a tutorial on how to create one? Many thanks!

like image 316
mcintyre321 Avatar asked Jun 09 '11 10:06

mcintyre321


1 Answers

Something like this?

using System; using System.Collections.Generic; using System.Dynamic;  public class NullingExpandoObject : DynamicObject {     private readonly Dictionary<string, object> values         = new Dictionary<string, object>();      public override bool TryGetMember(GetMemberBinder binder, out object result)     {         // We don't care about the return value...         values.TryGetValue(binder.Name, out result);         return true;     }      public override bool TrySetMember(SetMemberBinder binder, object value)     {         values[binder.Name] = value;         return true;     } }  class Test {     static void Main()     {         dynamic x = new NullingExpandoObject();         x.Foo = "Hello";         Console.WriteLine(x.Foo ?? "Default"); // Prints Hello         Console.WriteLine(x.Bar ?? "Default"); // Prints Default     } } 

I expect the real ExpandoObject is rather more sophisticated than this, but if this is all you need...

like image 153
Jon Skeet Avatar answered Sep 20 '22 15:09

Jon Skeet