Skip to content

CS8601 while mapping properties annotated with MaybeNullAttribute #2192

@hugoqribeiro

Description

@hugoqribeiro

Please do the checklist before filing an issue:

  • I have read the documentation, including the FAQ
  • I can reproduce the bug using the latest prerelease version
  • I have searched existing discussion and issue to avoid duplicates

Describe the bug

Generated code produces compilation error CS8601 Possible null reference assignment when:

  • Using nullable reference types
  • Using [MaybeNull] attribute

Any option to have the mapper consider the MaybeNull attribute in the source property?

Declaration code

public partial class OriginalType
{
    [MaybeNull]
    public string Name { get; set; } = default!;
}

public partial class MappedType
{
    [MaybeNull]
    public string Name { get; set; }
}

[Mapper]
internal partial class OneMapper
{
    public partial MappedType Map(OriginalType source);
}

Actual relevant generated code

internal partial class OneMapper
{
    [global::System.CodeDom.Compiler.GeneratedCode("Riok.Mapperly", "4.3.1.0")]
    public partial global::MapperlyBug.MappedType Map(global::MapperlyBug.OriginalType source)
    {
        var target = new global::MapperlyBug.MappedType();
        target.Name = source.Name;
        return target;
    }
}

Expected relevant generated code

internal partial class OneMapper
{
    [global::System.CodeDom.Compiler.GeneratedCode("Riok.Mapperly", "4.3.1.0")]
    public partial global::MapperlyBug.MappedType Map(global::MapperlyBug.OriginalType source)
    {
        var target = new global::MapperlyBug.MappedType();
        target.Name = source.Name!;
        // or
        //if (source.Name != null)
        //{
        //    target.Name = source.Name;
        //}
        return target;
    }
}

Environment (please complete the following information):

  • Mapperly Version: 4.3.1
  • Nullable reference types: enabled
  • .NET Version: 10.0.201
  • Target Framework: net10.0
  • C# Language Version: 14.0
  • IDE: VS 2026

Additional context

Changing the original code to use required properties is not an option because it would change the semantics of a large existing code base (forcing setting a bunch of properties at object initialization).
Additionally, most of the real classes are used as REST payloads (JSON serialization) and are also annotated with the [Required] attribute.
99,9% of the times using the null forgiving operator would be fine because the source of the mapping has already been validated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions