keenns12 keenns12 - 1 year ago 67
C# Question

Mapping items from one Class to Another if Items are Equivalent

Say I have one class that looks like this:

public class Person
public string Name {get; set;}
public int Number {get; set;}

And another that looks like this:

public class Dog
public string Name {get; set;}
public int Number {get; set;}

They are two different classes, but they happen to have the exact same elements (a string called
and an int called

Is there an easy way in C# to, say, if I had an instance of 'Person' to then create an instance of
with the same Name and Number?

For example if I had:

Person person = new Person();
person.Name = "George";
person.Number = 1;

I know I can't simply go:

Dog dog = person;

Because they are two different types. But is there a way in C# to check "oh, if they have the same element, set the same elements of
to equal that of
But I feel there has to be an easier way than doing something like:

dog.Name = person.Name;
dog.Number = person.Number;

Especially if the class has a LOT of elements. Also if anyone is wondering, these two different classes are in two different pieces of the API, so I can't simply make them related either. Thanks for any help!

Answer Source

You can use AutoMapper:

public Dog UsingAMR(Person prs)
    var config = new MapperConfiguration(cfg =>
        cfg.CreateMap<Person, Dog>();
    IMapper mapper = config.CreateMapper();
    return mapper.Map<Person, Dog>(prs);

Then you can easily:

Person ps = new Person {Name = "John", Number = 25};
Dog dog = UsingAMR(ps);

Just don't forget to install AutoMapper first from the package manager console as mentioned in the reference:

  1. From Tools menu click on NuGet Package Manager ==> Package Manager Console
  2. Then type the following command:

    PM> Install-Package AutoMapper
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download