I've been using AutoMapper to map between an interface and a concrete implementation of that interface. I assumed that if the type that I passed in to AutoMapper's Map<TDestination>
method was the same as the return type, then the original object would be returned (as a sort of short-circuiting operation). My assumption was wrong: indeed, after looking I noticed the documentation for that method explicitly states:
Execute a mapping from the source object to a new destination object. The source type is inferred from the source object. (bold emphasis mine)
I knocked-up this quick console app just to verify:
using System;
using AutoMapper;
namespace ConsoleApplication
{
class Program
{
interface IFoo
{
string Bar { get; }
}
class Foo : IFoo
{
public string Bar { get; set; }
}
static void Main(string[] args)
{
Mapper.CreateMap<IFoo, Foo>();
IFoo a = new Foo { Bar = "baz" };
Foo b = Mapper.Map<Foo>(a);
Console.WriteLine(Object.ReferenceEquals(a, b)); // false
}
}
}
Now that I know about this behaviour I can optimize around it for my particular use-case, but I was wondering if there is an alternate way of using AutoMapper whereby it will "short-circuit" in the way described above (ie. give me back the original object if the type is the same as the target type that I want)?