Search code examples
c#automapper

Which is the best approach? AutoMapper against implicit (C# Reference)


Automapper is a way to match types, ideally when you want to map a model and its viewmodel. But is this not the same approach that we can make with implicit in C#? (Suppose that both model have the same properties but with different names, on this case, you need to specify in AutoMapper which is linked between models)

With autommaper we have

public class Employee
{
    public string Name { get; set; }
    public string Email { get; set; }
}

public class EmployeeViewItem
{
    public string Name { get; set; }
    public string Email { get; set; }
}

Usually we do:

Employee employee = new Employee
{
    Name = "John SMith",
    Email = "[email protected]"
}

EmployeeViewItem viewItem = new EmployeeViewItem();
viewItem.Name = employee.Name;
viewItem.Email = employee.Email;

with AutoMapper

 EmployeeViewItem employeeVIewItem = Mapper.Map<Employee, EmployeeViewItem>(employee); 

Now, with the implicit C# Reference

public class Employee
{
    public static implicit operator EmployeeViewItem(Employee employee)
    {
         EmployeeViewItem viewItem = new EmployeeViewItem();
         viewItem.Name = employee.Name;
         viewItem.Email = employee.Email;
         return viewItem;
    }

    public static implicit operator Employee(EmployeeViewItem ev)
    {
        var e = new Employee();
        e.Name = ev.Name;
        e.Email = ev.Email;
        return e;
    }
}

Solution

  • AutoMapper uses reflection to map properties (slight performance overhead), allows advanced custom rules for mapping and requires 1 line of code in basic (common?) scenarios.

    Implicit operators require you to specify each property, are prone to errors (adding a new property but not adding it to the operator), are more difficult to setup for multiple types, create lots of useless code and even in the most basic setup you still have N lines of code where N is the amount of properties.

    I think it speaks for itself.