Quoter
Quoter

Reputation: 4302

Cast one object to another

I have got two user defined CLR objects which are identical and only differ in name, for example this code:

public class Person
{
  public string Name { get; set; }
  public string Address { get; set; }
  public string LastName { get; set; }
  public string ETC { get; set; }
}

public class PersonData
{
  public string Name { get; set; }
  public string Address { get; set; }
  public string LastName { get; set; }
  public string ETC { get; set; }
}

I know that this can be done by creating an object from either of these CLR's and than pass all properties one by one to it.

But is there another way? I got a few CLR's that are pretty big, 15+ properties.

[Edit] Some more context. The classes where already there. I generated a model from the database using EntityFramework. The database has almost the exact same structure as the classes.

Also, it's a lot of code that was already there. These classes also inherit from several interfaces etc. Refactoring now is not an option, so i'm looking for an easy fix for now.

Upvotes: 5

Views: 4948

Answers (3)

BlackBear
BlackBear

Reputation: 22979

And, just for the sake of completeness, here's what it looks like with reflection:

var a = new Person( ) { LastName = "lastn", Name = "name", Address = "addr", ETC = "etc" };
var b = new PersonData( );

var infoPerson = typeof( PersonData ).GetProperties( );
foreach ( PropertyInfo pi in typeof( Person ).GetProperties( ) ) {
    object value = pi.GetValue( a, null );
    infoPerson.Single( p => p.Name == pi.Name )
        .SetValue( b, value, null );
}

Upvotes: 2

Geeky Guy
Geeky Guy

Reputation: 9399

If you are the author of those classes, you could have them implement the same interface, or even better, inherit from the same class. That way you don't have to copy values from one to another - just use a reference to their parent type. Remember, having couples of unrelated types which have exactly the same members is a sure sign that you need to rethink your design ASAP.

Upvotes: 5

Eli Algranti
Eli Algranti

Reputation: 9007

Assumming you don't want both classes to inherit from an interface you can try Automapper it's a library for automatically mapping similar classes.

Upvotes: 9

Related Questions