Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast one object to another

Tags:

c#

casting

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.

like image 290
Quoter Avatar asked Sep 06 '13 21:09

Quoter


3 Answers

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.

like image 163
Eli Algranti Avatar answered Sep 23 '22 17:09

Eli Algranti


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.

like image 44
Geeky Guy Avatar answered Sep 22 '22 17:09

Geeky Guy


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 );
}
like image 23
BlackBear Avatar answered Sep 25 '22 17:09

BlackBear