Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper returns reference to the same object when mapping sequences to arrays

Tags:

c#

automapper

I have an extension method for IEnumerable<T>, which maps sequence items and returns an array of clones:

public static class AutoMapperExtensions
{
    public static T[] MapToArray<T>(this IEnumerable<T> sequence)
    {
        return Mapper.Map<T[]>(sequence);
    }
}

Here's code sample, whose behavior is weird from my point:

        Mapper.CreateMap<SomeClass, SomeClass>();
        Mapper.AssertConfigurationIsValid();

        // clone list members and store them into array
        var list = new List<SomeClass>
        {
            new SomeClass { MyProperty = 1 },
            new SomeClass { MyProperty = 2 },
        };

        // works fine
        var array = list.MapToArray();

        // let's map array again
        var newArray = array.MapToArray();

        // ...and ensure, that new array was created;
        // this fails, because Automapper returns reference to the same array
        Debug.Assert(array != newArray); 

It seems to me, that last result is wrong. While I'm expecting, that mapper will create new array of clones, it just returns the reference to the same array.

Is this documented elsewhere or this is a bug?

like image 770
Dennis Avatar asked Sep 07 '25 22:09

Dennis


1 Answers

So this isn't a bug - when AutoMapper sees two objects that are assignable, it will simply assign them. If you want to override that behavior, create a map between the two collection types.

like image 96
Jimmy Bogard Avatar answered Sep 10 '25 15:09

Jimmy Bogard