Wednesday, 16 June 2010

Using the IMapper interface with the System.Converter delegate

Recently I wrote a post about using a standard mapping interface for your mappers which gave the added benefit of providing an easy way to write an extension method for mapping enumerable. As it turns out it also has the added benefit in fitting in with the System.Converter delegate signature in that the signature of the Map method of the IMapper interface is the same as the System.Converter delegate.

Whilst the extension method provides a way of mapping enumerations there may be cases where it is more preferable to us the Array.ConvertAll and the List<T>.ConvertAll methods. The Array method is static and the List is instance but each of these take in a System.Converter delegate and map to a typed array and a typed list respectively. All of which means we can do the following:

IMapper<ObjectA, ObjectB> myAToBMapper = new MyAToBMapper();
ObjectA[] aArray = { new ObjectA(), new ObjectA() };
ObjectB[] bArray = Array.ConvertAll<ObjectA, ObjectB>(aArray, myAToBMapper.Map);
List<ObjectA> aList = new List<ObjectA> { new ObjectA(), new ObjectA() };
List<ObjectB> bList = aList.ConvertAll<ObjectB>(myAToBMapper.Map);
// Or
var aToBConverter = new Converter<ObjectA, ObjectB>(myAToBMapper.Map);
bArray = Array.ConvertAll(aArray, aToBConverter);
bList = aList.ConvertAll(aToBConverter);

Whilst I prefer the synatax of MapAll this does show that the IMapper interface has versatility elsewhere in the core library.

No comments:

Post a Comment