Search code examples
c#oopnullable-reference-types

DTO constructors when nullable reference type enabled


Some scenarios in my code is that I have to get an object from an external service, deserialize it and return it to the front end. My code includes nullable reference from C# 8 and compiler complains about such DTOs without constructor. Any of such fields cannot be null if entity is real.

I don't need someone to be able to create such objects manually, but when using the deserializer I need the type to have an empty constructor and fields with public setters. Because of this I have to write a lot of ugly code. Is there a better approach in this scenario or some syntactic sugar to reduce the infra-structural code?

public class AddressRF
{
    public AddressRF() // used implicitly
    {
        ZipCode = null!;
        RegionCode = null!;
        RegionName = null!;
        District = null!;
        City = null!;
        Settlement = null!;
        Street = null!;
        House = null!;
        Bulk = null!;
        Flat = null!;
        KladrCode = null!;
        HouseRaw = null!;
        BulkRaw = null!;
        FlatRaw = null!;
    }

    public string ZipCode { get; set; } 
    public string RegionCode { get; set; } 
    public Toponym RegionName { get; set; } 
    public Toponym District { get; set; } 
    public Toponym City { get; set; } 
    public Toponym Settlement { get; set; } 
    public Toponym Street { get; set; } 
    public Toponym House { get; set; } 
    public Toponym Bulk { get; set; } 
    public Toponym Flat { get; set; } 
    public string KladrCode { get; set; } 
    public string HouseRaw { get; set; } 
    public string BulkRaw { get; set; } 
    public string FlatRaw { get; set; }
}

Solution

  • You have few options

    1 - Declare properties as Nullable

    public string? ZipCode { get; set; }
    

    2 - Add nullable disable around the constructor

    #nullable disable
            public AddressRF() // used implicitly
            {
            }
    #nullable enable
    

    3 - Set the value on the property level

    public string ZipCode { get; set; } = string.Empty; // or = null!