Object validation with nullable reference types in C#

1.5k Views Asked by At

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;
    }
}
2

There are 2 best solutions below

13
On

It seems that doesn't need to declare get setter explicitely, so you can declare the public member by any default value, and let the compiler doing its job for you perfectly. :D

public string ConnectionString = null;
0
On

As per the docs @ https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references

The compiler doesn't add any null checks or other runtime constructs in a nullable context. At runtime, a nullable reference and a non-nullable reference are equivalent.

So, when a DTO is deserialized at runtime, you may not have any additional constructs to denote whether a field is Nullable reference type or non-nullable reference type at atleast at the time of writing this answer.