0

I have an application with non-nullable reference types enabled and am using a mediator pattern.

In the following scenario I'm trying to create a TodoItem. I have a validator that ensures that the Title property of CreateTodoItemCommand is not empty however, the CreateTodoItemCommandHandler has no knowledge of this and so I get a compile time error that I'm referencing a potentially nullable property. I can silence this by using the null-forgiving operator var todoItem = new TodoItem(request.Title!); but this feels a bit like a hack. How are others working around these issues?

public class CreateTodoItemCommand : IRequest<int>
{
    // bound via a web request so can come through as null
    public string? Title { get; set; }
}

public class CreateTodoItemCommandValidator : AbstractValidator<CreateTodoItemCommand>
{
    public CreateTodoItemCommandValidator()
    {
        RuleFor(v => v.Title)
            .MaximumLength(200)
            .NotEmpty();
    }
}

public class CreateTodoItemCommandHandler : IRequestHandler<CreateTodoItemCommand, int>
{
    public async Task<int> Handle(CreateTodoItemCommand request, CancellationToken cancellationToken)
    {
        // [CS8604] Possible null reference argument for parameter 'title' in 'TodoItem(string title)'.
        var todoItem = new Todo(request.Title);

        // omitted
    }
}

public class Todo
{
    public Todo(string title)
    {
       
    }
}
kimsagro
  • 15,513
  • 17
  • 54
  • 69
  • Does it make a difference if you remove the `?` from `string?`? Strings have always been nullable, although I see [there is new stuff in C# 8](https://stackoverflow.com/questions/32853482/how-can-i-make-my-string-property-nullable). – Andrew May 19 '22 at 01:13
  • 1
    Why do you have the nullable type If the code doesn't require it? – Train May 19 '22 at 03:59
  • You show `new TodoItem(request.Title)` and a `Todo` constructor. Did you mean both to be the same? Why does the latter expect a `string` whlie `Title` is `string?`? – Andrew May 19 '22 at 06:06
  • Updated the question. Todo requires a non null title which is guaranteed as the shown validator will validate and throw if that's not the case. The title coming from CreateTodoItemCommand must be nullable as it's being bound to a web request so no guarantee that someone doesn't post an empty body – kimsagro May 19 '22 at 07:03
  • Can you use a different property? Like `public string NonNullTitle { get { return Title ?? string.Empty; } }` – Andrew May 19 '22 at 21:38
  • @kimsagro, still there? – Andrew Jun 02 '22 at 21:12

0 Answers0