Josh Santangelo
Josh Santangelo

Reputation: 918

Casting between similar types in C#

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

Answers (3)

CaffGeek
CaffGeek

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

Adam Maras
Adam Maras

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

Jon Skeet
Jon Skeet

Reputation: 1500525

You have to either do hacking with reflection (I have a PropertyCopy class in MiscUtil which can help) or use dynamic typing from C# 4.

As far as .NET is concerned, these are completely separate types.

Upvotes: 7

Related Questions