Skip to main content

Derived types and interfaces

Mapperly supports interfaces and base types as mapping sources and targets, for both new instance and existing target mappings. To do this, Mapperly needs to know which derived types exist. This can be configured with the MapDerivedTypeAttribute:

[Mapper]
public static partial class ModelMapper
{
[MapDerivedType<Banana, BananaDto>] // for c# language level ≥ 11
[MapDerivedType(typeof(Apple), typeof(AppleDto))] // for c# language level < 11
public static partial FruitDto MapFruit(Fruit source);
}

abstract class Fruit {}
class Banana : Fruit {}
class Apple : Fruit {}

abstract class FruitDto {}
class BananaDto : FruitDto {}
class AppleDto : FruitDto {}

All source types provided to the MapDerivedTypeAttribute need to implement or extend the type of the mapping method parameter. All target types provided to the MapDerivedTypeAttribute need to implement or extend the mapping method return type. Each source type has to be unique but multiple source types can be mapped to the same target type.

Configuration attributes on methods with MapDerivedTypeAttributes are used to build the mapping of each derived types combination unless there is a user defined mapping method for exactly this source/target type combination.