Question

I have some code that works with ExpandoObjects populated by database calls. Invariably some of the values are nulls. When I look at the objects as an ExpandoObject, I see all the keys and values (nulls included) in the underlying dictionary. But if I try to access them through a dynamic reference, any key that has a corresponding null value does not show up in the dynamic view of the object. I get an ArgumentNullException when I try to access it via property syntax on the dynamic reference.

I know I could work around this by working directly with an ExpandoObject, adding a bunch of try catches, mapping the expando to a concrete type, etc., but that kind of defeats the purpose of having this dynamic object in the first place. The code that consumes the dyanmic object would work fine if some of the properties had null values. Is there a more elgent or succinct way of "unhiding" these dynamic properties that have null values?

Here's code that demonstrates 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);
Was it helpful?

Solution

The problem you are having is that the dynamic runtime overload invocation is picking string .Format(format, params object[] args) instead of the intended string.Format(string format, object arg0) a simple cast will switch to a static invocation of string.Format and fix it.

string someString2 = string.Format("{0}", (object)dynamicRef.NulledProperty);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top