The dynamic view of ExpandoObjects hides null-value properties

I have code that works with ExpandoObjects populated with database calls. Invariably, some of the values ​​are zeros. When I look at objects as ExpandoObject, I see all the keys and values ​​(including zeros) in the base dictionary. But if I try to access them through a dynamic link, any key that has a null value will not be displayed in the dynamic representation of the object. I get an ArgumentNullException when I try to access it through the syntax of the properties in a dynamic link.

I know that I could get around this by working directly with ExpandoObject, adding a bunch of catch attempts, matching expando with a specific type, etc., but this view defeats the goal of having this dynamic object in the first place. The code that the dyanmic object consumes will work fine if some properties have null values. Is there a more elgetic or laconic way of “revealing” these dynamic properties that have zero values?

Here is a code demonstrating my "problem"

dynamic dynamicRef = new ExpandoObject();
ExpandoObject expandoRef = dynamicRef;

dynamicRef.SimpleProperty = "SomeString";
dynamicRef.NulledProperty = null;

string someString1 = string.Format("{0}", dynamicRef.SimpleProperty);

// My bad; this throws because the value is actually null, not because it isn't
// present.  Set a breakppoint and look at the quickwatch on the dynamicRef vs.
// the expandoRef to see why I let myself be led astray.  NulledProperty does not
// show up in the Dynamic View of the dynamicRef
string someString2 = string.Format("{0}", dynamicRef.NulledProperty);
+5
source share
1 answer

, , , string .Format(format, params object[] args) string.Format(string format, object arg0), string.Format .

string someString2 = string.Format("{0}", (object)dynamicRef.NulledProperty);
+3

All Articles