I’m learning model binding and validation for C# .NET 8 Razor Pages. I set up a simple input model to test validation (from ASP.NET Core Razor Pages in Action, Mike Brind):
public class InputModel
{
[Required]
public string CountryName { get; set; }
[Required, StringLength(2, MinimumLength = 2)]
public string CountryCode { get; set; }
}
However I get the following compiler warning:
Warning CS8618 Non-nullable property 'CountryName' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
, same for CountryCode
.
It’s easy enough to understand I should assign a value to CountryName
and CountryCode
, or set them to nullable, but what is most correct and why?
public string CountryName { get; set; } = default!;
public string CountryName { get; set; } = string.Empty;
public string CountryName { get; set; } = "";
public string? CountryName { get; set; }
public string? CountryName { get; set; } = default;
- Something else