简体   繁体   中英

C#8 nullable and non-nullable reference types - nullable output only if input is nullable

I have a bunch of extension methods that convert my entities to DTOs like the following.

public static LocationDto? ToDto(this Location? @this)
{
    if (@this == null) return null;

    return new LocationDto
            {
                Id = @this.Id,
                Text = @this.Name,
                ParentId = @this?.Parent?.Id,
            };
}

The issue here is that if you pass not nullable entity still receive a nullable and you cannot define a public static LocationDto ToDto(this Location @this) because they would be compiled to the same method.
Also, I don't like to use ! for the time I am calling it. So the following is not my answer.

Location entity = AMethod();
LocationDto dto = entity.ToDto()!;

Is there an attribute or syntax to tell the compiler how this method behaves? Somehting like:

public static [NullableOnlyIfInputIsNull] LocationDto? ToDto(this Location? @this)

The attribute you are asking for is NotNullIfNotNullAttribute

The attribute accepts the name of the parameter you use to infer nullity.

In your case this would look like:

using System.Diagnostics.CodeAnalysis;

// ...

[return:NotNullIfNotNull("this")]
public static LocationDto? ToDto(this Location? @this)
{
    // Your code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM