5

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);
jbtule
  • 31,383
  • 12
  • 95
  • 128
Tim Trout
  • 1,062
  • 12
  • 20
  • ExpandoObject's can store null values, and pull them out, are you sure of what is causing the argument null exception? – jbtule Mar 06 '12 at 21:51
  • 1
    If the key is present in the `ExpandoObject`, it will return it whether it's `null` or not. If it's not present, it will throw a `RuntimeBinderException`. It won't throw `ArgumentNullException`, so there must be some error in your code. Could you show us the code that throws? – svick Mar 07 '12 at 00:32
  • OK, I think I'm just being fooled by the Visual Studio watch window. The code is throwing an ArgumentNullException because the value is actually null, not because the property is "missing". When I set a watch on the dynamic reference, it doesn't show the property if it has a null value. If I put a watch watch the ExpandoObject reference to the same object, it shows the property name in the underlying key list. – Tim Trout Mar 07 '12 at 01:30

1 Answers1

3

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);
jbtule
  • 31,383
  • 12
  • 95
  • 128