2

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)
2
  • c#-9.0 has nullable reference types. Commented Nov 17, 2020 at 18:24
  • @rafaelgonzalez yes, you are right. C# has it since C#8. Commented Nov 17, 2020 at 22:00

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.