0

The Model:

public class ErrorMessage
{
    public string StatusCode { get; set; } = "400";
    public List<string> Message { get; set; }
}

I initialized the model here. When it goes to add the string to it there is always a null exception/reference error. I'm completely doing this wrong?

 ErrorMessage errorMessage = new ErrorMessage();

 errorMessage.Message.Add("The transaction could not be processed");
AJ Jones
  • 55
  • 6
  • 1
    Is the list initialized? – Zyan Nov 16 '21 at 20:22
  • 1
    Fun fact, just because you made a new `ErrorMessage`, doesn't mean that `Message` is initialized. – gunr2171 Nov 16 '21 at 20:22
  • 2
    `public List Message { get; set; } = new();` or `public List Message { get; set; } = new List();` you need to initialize this property before trying to do anything related with it. – Trevor Nov 16 '21 at 20:23
  • 1
    @zaggler Even better, `public List Message { get; private set; } = new();`. No one outside the type needs set access to the property. Even if you want to add or remove items, that's still a `get` operation. – Joel Coehoorn Nov 16 '21 at 20:58
  • @JoelCoehoorn I agree with you, thanks for the feedback! – Trevor Nov 16 '21 at 21:00

0 Answers0