Reputation: 918
I have two types that have the same members, but different names. Is there an easy or standard way to cast between them, or do I have to do some serious hacking with reflection?
Upvotes: 2
Views: 202
Reputation: 22054
This is far from perfect, but I use this extension method to copy properties with the same name between objects based on a common interface
public static T CopyTo<T>(this T source, T target) where T : class
{
foreach (var propertyInfo in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
propertyInfo.SetValue(target, propertyInfo.GetValue(source, null), null);
}
return target;
}
Usage is something like
var internationalCustomer = new InternationalCustomer();
var customer = (Customer)internationalCustomer.CopyTo<ICustomer>(new Customer());
where InternationalCustomer and Customer both have to have implemented ICustomer.
Upvotes: 1
Reputation: 26853
You could create an interface
that describes both of the types. Make each type implement the interface, then use the interface instead of a specific type when working in code that can deal with either type.
Upvotes: 9