Karthik Balasubramanian
Karthik Balasubramanian

Reputation: 1157

Transforming between objects in C#

I have what seems to be a simple problem, but am unable to come up with a clean solution. I have a two classes which looks like below

Class Person{
    String name{get; set;}
    int age{get; set;}
}


Class Alien{
    String alienName{ get; set}
    int alienAge{get; set;}
}

These classes are thirdparty classes that I have to use, have no control over. But at some point I would want to be able to construct a Alien object given a Person object and vice versa. I have only two properties in my example. In real life I may have upto 50 properties for both Alien and Person.

Alien is not a subset of Person and Person is not a subset of alien. Those are just two different objects. What do you guys think is the best way to transform these objects between each other. I don't want to laboriously write a copy method that takes in each property and sets its equivalent property in the other. Since the method names can be vastly different between those two classes, I don't think I might be able to use reflection either. Ideally am looking for something which would externalize the copy procedure so that if something changes in Alien or Person object in the future, I wouldn't have to change my logic.

Any suggestions?

Thanks K

Upvotes: 2

Views: 2458

Answers (3)

Ria
Ria

Reputation: 10347

Use Interfaces. If you have an Interface, certain properties that you must to be copied are already defined:

Interface ISubject
{
    // properties
    String name {get; set;}
    int age {get; set;}
}

Class Person : ISubject
{
    // contractors
    public Person ()
    {
        ...
    }

    public Person (ISubject subject)
    {
         name = subject.name;
         age = subject.age;
    }
    ...
}

Class Alien : ISubject
{
    // contractors
    public Alien ()
    {
        ...
    }

    public Alien (ISubject subject)
    {
         name = subject.name;
         age = subject.age;
    }
    ... 
}

and when you using:

var person = new Person();
...
ISubject subject = (ISubject) person;
var name = subject.name;

or

var person = new Person();
...
Alien subject = new Alien(person);
var name = alien.name;

Upvotes: 2

Luis Specian
Luis Specian

Reputation: 104

You can try http://code.google.com/p/nutil/ , there is a class named BeanUtils, that have a method to copy properties.

Upvotes: 0

Lee
Lee

Reputation: 144136

You might want to look at AutoMapper

Upvotes: 4

Related Questions