Im trying to clone an AnonymousType and enconter some strange behavior.
could anyone tell me why and also tell me a solution. Here is a test code.
public static T DeepClone<T>(this T objectToBeCloned) where T : class
{
// this will always return null.
return Clone(objectToBeCloned) as T;
// if i try, it will work somehow
// var o = Clone(objectToBeCloned) as dynamic;
// if I try, will get an exception cant cast
// ExpandoObject to AnonymousType even thaugh i could cast it to dynamic
// var o = (T)Clone(objectToBeCloned);
}
// the clone method
public static object Clone(this object objectToBeCloned){
object resObject;
if (primaryType.IsAnonymousType()) // dynamic types
{
var props = FastDeepClonerCachedItems.GetFastDeepClonerProperties(primaryType);
resObject = new ExpandoObject();
var d = resObject as IDictionary<string, object>;
foreach (var prop in props.Values)
{
var item = prop.GetValue(objectToBeCloned);
if (item == null)
continue;
var value = prop.IsInternalType ? item : Clone(item);
if (!d.ContainsKey(prop.Name))
d.Add(prop.Name, value);
}
return resObject;
}
dynamic test = { p1="sd" };
var v =test.DeepClone(test);
// v is always null in this case dont understand why