Is there a way to convert a dynamic or anonymous object to a strongly typed, declared object?

.NetC# 4.0Anonymous ClassDynamicobject

.Net Problem Overview


If I have a dynamic object, or anonymous object for that matter, whose structure exactly matches that of a strongly typed object, is there a .NET method to build a typed object from the dynamic object?

I know I can use a LINQ dynamicList.Select(dynamic => new Typed { .... } type thing, or I can use Automapper, but I'm wondering if there is not something specially built for this?

.Net Solutions


Solution 1 - .Net

You could serialize to an intermediate format, just to deserialize it right thereafter. It's not the most elegant or efficient way, but it might get your job done:

Suppose this is your class:

// Typed definition
class C
{
    public string A;
    public int B;
}

And this is your anonymous instance:

// Untyped instance
var anonymous = new {
    A = "Some text",
    B = 666
};

You can serialize the anonymous version to an intermediate format and then deserialize it again to a typed version.

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(anonymous);
var c = serializer.Deserialize<C>(json);

Note that this is in theory possible with any serializer/deserializer (XmlSerializer, binary serialization, other json libs), as long as the roundtrip is symmetric.

Solution 2 - .Net

Your question comes down to the question: can I convert one statically typed variable into another statically typed variable (from different inheritance chains)? and the answer, obviously, is No.

Why does your question come down to the above question?

  • Dynamic type usage compiles into using the Object type with reflection.
  • Your code receives Object in reality, that (in reality) contains value from one particular static type.

So, in fact, your code is dealing with the statically typed value, assigned to the Object, and treated as Dynamic at compile time. Therefore, the only case when you can convert one statically typed value into another [without reflection] is when they are part of the same inheritance chain. Otherwise, you are bound to using reflection explicitly (written by you) or implicitly (written by MS with Dynamic usage).

In other words, the following code will work at runtime only if the value assigned to the dynamic is derived from Person or is Person itself (otherwise the cast to Person will throw an error):

dynamic dPerson = GetDynamicPerson();
Person thePerson = (Person)dPerson;

That's pretty much it.

Fair to mention, you can copy the values byte by byte with unsafe code accessing the memory addresses (like in C++), but that to me is nothing better than reflection.

Solution 3 - .Net

Here we can convert an anonymous object to Dictionary

Dictionary<string, object> dict = 
    obj.GetType()
      .GetProperties()
      .ToDictionary(p => p.Name,  p => p.GetValue(obj, null));

Also you can cast an object using LINQ:

List<MyType> items = anonymousType.Select(t => new MyType(t.Some, t.Other)).ToList();

Solution 4 - .Net

If your object inherits from MarshalByRefObject you can use RealProxy.

Another alternative is to use Reflection but you may be limited by stuff not marked virtual and/or have to use interfaces. You could also have it copy the values, assuming the properties are writable and the empty constructor works for your case.

The actual answer to your question is no, there is no automatic way to treat a dynamic object as a specific type unless it is an instance of that type, nor is there any automatic facility to copy the values from a dynamic/anonymous object into an instance of a named class.

The runtime has no idea what is going on in the constructor or how the class is implemented internally, so any such facility would blow type safety out of the water. The whole point of dynamic is to allow duck typing/runtime dispatch/etc.

edit: If I misunderstood the question let me know, but I am assuming you want to treat a dynamic object as if it were an instance of SomeType.

In my own projects, I've used an Object Mapper class for this where it matches up the property names for writable properties and identical or coercible types so at least I didn't have to write 10,000 lines of boilerplate, though my source wasn't dynamic so I used Reflection.Emit/DynamicMethod to greatly speed it up.

Solution 5 - .Net

So, I am going to provide an answer to this question that assumes you will manually set the primitive variables. Say you have a Dictionary<string, dynamic> dict that contains the dynamic version of float x and a bool y. You can do:

float x = (float)dict["x"];
bool y = (bool)dict["y"];

If you wanted to do this for reference types, you can simply have a constructor for your class that does this conversion for every field.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionProfKView Question on Stackoverflow
Solution 1 - .NetGrimace of DespairView Answer on Stackoverflow
Solution 2 - .NetTengizView Answer on Stackoverflow
Solution 3 - .NetjheraxView Answer on Stackoverflow
Solution 4 - .NetrussbishopView Answer on Stackoverflow
Solution 5 - .NetRyan WickmanView Answer on Stackoverflow