Skip to content

Map|ShouldMap - set value to default(T) of given T source property #293

@lpussacq

Description

@lpussacq

Hello,
I've seen some weird behavior when using the shouldMap option of the Map method. The wiki page regarding this feature explains that if the condition is not met, the destination property is set to null or default value. But the default value seems to be the one of the property's source type.
For instance, given the following classes:

public class Dest {
  public DateTimeOffset? Start {get;set;}
}

public class Src {
  public DateTimeOffset Start {get;set;}
  public bool HasStart {get;set;}
}

and the given configuration

/*...*/
  NewConfig<Src, Dest>().Map(dest => dest.Start, src => src.Start, src => src.HasStart);
/*...*/

Adapting Src to Dest with HasStart = false will give use the following result: Dest.Start = 0 (because 0 is the default value for a DateTimeOffset which is the type given in the mapping).

One of the solution I found to prevent this issue in my code is to cast the given type of the src to the destination type :
NewConfig<Src, Dest>().Map(dest => dest.Start, src => src.Start as DateTimeOffset?, src => src.HasStart);
but this does not feel very natural.

To conclude, I am not sure if the issue comes from the code or the documentation. As explained, there is a easy fix for the time being, but maybe the wiki page could be updated accordingly or the code (depending of what feel more suitable)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions