keenns12 keenns12 - 2 months ago 8
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
'Name'
and an int called
'Number'
)

Is there an easy way in C# to, say, if I had an instance of 'Person' to then create an instance of
'Dog'
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
'Dog'
to equal that of
'Person'
.
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

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
    
Comments