Is there a way to convert a dynamic or anonymous object to a strongly typed, declared object?
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.
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.
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();