I have two objects and I want to merge them:
public class Foo
{
public string Name { get; set; }
}
public class Bar
{
public Guid Id { get; set; }
p
UNTESTED, but using the Reflection.Emit API, something like this should work:
public Type MergeTypes(params Type[] types)
{
AppDomain domain = AppDomain.CurrentDomain;
AssemblyBuilder builder =
domain.DefineDynamicAssembly(new AssemblyName("CombinedAssembly"),
AssemblyBuilderAccess.RunAndSave);
ModuleBuilder moduleBuilder = builder.DefineDynamicModule("DynamicModule");
TypeBuilder typeBuilder = moduleBuilder.DefineType("CombinedType");
foreach (var type in types)
{
var props = GetProperties(type);
foreach (var prop in props)
{
typeBuilder.DefineField(prop.Key, prop.Value, FieldAttributes.Public);
}
}
return typeBuilder.CreateType();
}
private Dictionary GetProperties(Type type)
{
return type.GetProperties().ToDictionary(p => p.Name, p => p.PropertyType);
}
USAGE:
Type combinedType = MergeTypes(typeof(Foo), typeof(Bar));