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!
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With