Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nullable required/init properties should use nullable coalescing initialization when mapping child. #589

Open
TimothyMakkison opened this issue Jul 23, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@TimothyMakkison
Copy link
Collaborator

TimothyMakkison commented Jul 23, 2023

When mapping nested children of a nullable property with MapProperty, Mapperly will use a nullable coalescing assignment expression to ensure that the parent is initialized and to prevent that a NullReferenceException does not occur.

This does not occur if the source member is required/init. Perhaps a nullable coalescing assignment could be inserted into the initializer to prevent errors from occuring.

Example of normal behaviour

[Mapper]
public static partial class Mapper
{
    [MapProperty("Value", "Nested.Value")]
    public static partial B Map(A src);
}

public class A { public int Value { get; set; } }

public class B { public C? Nested { get; set; } }

public class C { public int Value { get; set; } }

// Generates
public static partial global::Riok.Mapperly.Sample.B Map(global::Riok.Mapperly.Sample.A src)
{
    var target = new global::Riok.Mapperly.Sample.B();
    target.Nested ??= new();
    target.Nested.Value = src.Value;
    return target;
}

Desired behaviour

[Mapper]
public static partial class Mapper
{
    [MapProperty("Value", "Nested.Value")]
    public static partial B Map(A src);
}

public class A { public int Value { get; set; } }

public class B { public C? Nested { get; init; } }

public class C { public int Value { get; set; } }

// Generates
public static partial global::Riok.Mapperly.Sample.B Map(global::Riok.Mapperly.Sample.A src)
{
    var target = new global::Riok.Mapperly.Sample.B()
    {
        Nested ??= new global::Riok.Mapperly.Sample.C();
    };
    target.Nested.Value = src.Value;
    return target;
}

Current generation

public static partial global::Riok.Mapperly.Sample.B Map(global::Riok.Mapperly.Sample.A src)
{
    var target = new global::Riok.Mapperly.Sample.B();
    return target;
}
@latonz latonz added the enhancement New feature or request label Jul 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants