Let's say I have an configuration or DTO object with use of C# nullable reference object feature:
public class ServiceConfig
{
public string ConnectionString { get; set; }
public string? OptionalComment { get; set; }
}
With upper code I get compiler warning "CS8618: Non-nullable property 'ConnectionString' must contain a non-null value when exiting constructor. Consider declaring the property as nullable." Because this objects needs parameterless constructor I can add = null!
to get rid of the warning. But the problem is that object can still contain property with null value. Because I want to use this in a context of configuration and DTO's, there is an option to validate objects (in deserialization process) before they are passed to "real" objects.
How can I do it? It there a way where I can validate if object is valid by "Nullable references" notation? I see other option also with Data Annotations, but I use of this C# feature is a lot more attractive.
So, in fantasy I would like to have something like this:
public class ServiceConfig
{
public string ConnectionString { get; set; } = null!;
public string? OptionalComment { get; set; }
}
public class Deserializer
{
public static ServiceConfig Deserialize(string data)
{
var result = Json.Deserialize<ServiceConfig>(data);
var isObjectValid = result.IsValid(); // I want method something like this
if (!isObjectValid) throw new Exception("Deserialization error");
return result;
}
}