3

this might be an easy one but I am really not getting it.

As far as I understand: The most dynamic types ins C# rely on IDictionary<string,object>

I did a spike with WebMatrix.Data and I would like to cast my result to IDictionary<string,object> but this does not work... WebMatrix.Data query returns an IEnumerable<DynamicRecord> This is what I try to cast...

here is my naiv code ...

var o = (DynamicObject) webmatrixRecord; // No Exception but o is still DynamicRecord

var o = (IDictionary<string,object>) webmatrixRecord; // Runtime Binder Exception

var o = ((IDictionary<string,object>)((DynamicRecord)webmatrixRecord)) // InvalidCastException;

So what is a proper way to cast an Dynamic object?

WebMatrix.DynamicRecord: http://msdn.microsoft.com/de-de/library/webmatrix.data.dynamicrecord(v=vs.111).aspx

Dynamics.DynamicRecord: http://msdn.microsoft.com/de-de/library/system.dynamic.dynamicobject(v=vs.111).aspx

silverfighter
  • 6,762
  • 10
  • 46
  • 73

1 Answers1

1

The most dynamic types ins C# rely on IDictionary<string,object>

Not necessarily. ExpandoObject does, but there are plenty of other ways of being dynamic, and DynamicObject doesn't.

Note that reference conversion casting doesn't change the type of an object. So where you've got this line:

var o = (DynamicObject) webmatrixRecord; 

... the type of the variable will be DynamicObject, but that doesn't change the type of the object that the value of o refers to.

For your other casts, it seems that it just doesn't implement IDictionary<string, object>, so you can't cast to it. You could use DynamicObject.GetDynamicMemberNames to get the dynamic names, and then use DynamicObject.TryGetMember to get the values. It's not ideal though - I would personally try to avoid even having the requirement, if possible...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks for the reply ... I choosed DynamicObject only because DynamicRecord inherits from it and I thought it brings me closer :-/ I need an ExpandoObject or and IDictionary from DynamicRecord... but since u said there is no cast I have to write something... – silverfighter Oct 18 '13 at 14:19
  • @silverfighter: Does `DynamicRecord` itself expose anything? I can't see anything after a quick browse - so you may well need to call `GetDynamicMemberNames` and then `TryGetMember` in order to build your dictionary. – Jon Skeet Oct 18 '13 at 14:25
  • As far as the open source version von WebMatrix.Data says .. I take your bet with GetDynamicMemberNames and TryGetMember... http://aspnetwebstack.codeplex.com/SourceControl/latest#src/WebMatrix.Data/DynamicRecord.cs – silverfighter Oct 18 '13 at 14:28