2

Is there an easy way to copy everything from a strongly typed object into a dynamic one? The target has to be a DynamicObject as determined by a 3rd party library I'm using. Everything from TypedModel needs to go into MyDynamicObject at runtime.

public class MyDynamicObject : DynamicThirdPartyObject
{ }

public class TypedModel
{
    public string text { get; set; }

    public int number { get; set; }

    public List<SomeOtherModel> someList { get; set; }
}

Existing solutions I found on SO all match up properties between typed classes.

EDIT

Found a simple solution based on FastMember:

public void CopyProperties(object source, DynamicObject target)
{
    var wrapped = ObjectAccessor.Create(target);
    foreach (var prop in source.GetType().GetProperties())
    {
        wrapped[prop.Name] = prop.GetValue(source);
    }
}
Benjamin E.
  • 5,042
  • 5
  • 38
  • 65
  • Have you tried just using reflection? – Marc Gravell Jan 16 '15 at 08:32
  • I think you need to take a look at the `Expando Object`.http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx – Mahesh Jan 16 '15 at 08:32
  • possible duplicate of [Adding members to a dynamic object at runtime](http://stackoverflow.com/questions/3934161/adding-members-to-a-dynamic-object-at-runtime) – Mahesh Jan 16 '15 at 08:33
  • This might be same as http://stackoverflow.com/questions/3934161/adding-members-to-a-dynamic-object-at-runtime – Mahesh Jan 16 '15 at 08:33
  • make use of prototype design pattern....and use ICloneable for that and make use of reflection – Pranay Rana Jan 16 '15 at 08:33
  • @Coder of Code: It has to be a `DynamicObject`. I'm using Postal and need to inherit from this class https://github.com/andrewdavey/postal/blob/master/src/Postal/Email.cs – Benjamin E. Jan 16 '15 at 08:45

1 Answers1

1

I propoes to use reflection.

suppose you make following declaration:

public class MyDynamicObject : DynamicThirdPartyObject
{ }

public class TypedModel
{
    public string text { get; set; }

    public int number { get; set; }

    public List<SomeOtherModel> ListOtherModel { get; set; }
}

Lets say you want to get properties of instance:

typedModel.GetType().GetProperties();

Another possible situation is if you want to copy type:

typeof(TypedModel).GetProperties();

TypedModel typeModel = new TypedModel {number = 1, text = "text1", 
ListOhterModel = new List()
};
foreach(var prop in typeModel.GetType().GetProperties()) 
{
    Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(typeModel, null));
}

And if you need to go through hierarchy, maybe you need to use recursion, in order to go through nested types, I mean you can use reflection for copying all members of SomeOtherModel.

Yuriy Zaletskyy
  • 4,983
  • 5
  • 34
  • 54