Skip to content

Unable to map nullable primitive types (string? to bool?) using custom MapWith delegate #992

Description

@vzalamea

What am I missing?

Image
using Mapster;
using MapsterMapper;

TypeAdapterConfig config = new TypeAdapterConfig();
config.NewConfig<string?, bool?>().MapWith(src => Helper.ParseToNullableBool(src));
config.Compile();

Mapper mapper = new Mapper(config);

Source source = new Source { Prop1 = "yes" };
Destination destination = mapper.Map<Destination>(source);

Console.ReadLine();

static class Helper
{
    public static bool? ParseToNullableBool(string? value)
    {
        if (string.IsNullOrWhiteSpace(value))
            return null;

        return value.Trim().ToLower() switch
        {
            "true" or "t" or "yes" or "1" => true,
            "false" or "f" or "no" or "0" => false,
            _ => null
        };
    }
}

class Source
{
    public string? Prop1 { get; set; }
}

class Destination
{
    public bool? Prop1 { get; set; }
}

converting non-nullable string to non-nullable bool works fine

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions