I have a DTO which is populated by reading from a DynamoDB table. Say it looks like this currently:
public class Item
{
public string Id { get; set; } // PK so technically cannot be null
public string Name { get; set; } // validation to prevent nulls but this doesn't stop database hacks
public string Description { get; set; } // can be null
}
Is there any best practice developing for dealing with this? I'd rather avoid a non-parameterless constructor since that plays badly with the ORM in the Dynamo SDK (as well as others).
It seems strange to me to write public string Id { get; set; } = ""; because this will never happen since Id is a PK and can never be null. What use would "" be even if it did somehow anyway?
So any best practice on this?
- Should I mark them all as
string?to say they can be null even though some never should be. - Should I initialise
IdandNamewith""because they should never be null and this shows the intent even though""would never be used. - Some combination of above
Please note: this is about C#8 nullable reference types If you don't know what they are best not answer.
#pragma warning disable CS8618at the top of the file. - Twenty= "", you can use= null!to initialize a property that you know will never effectively benull(when the compiler has no way of knowing that). IfDescriptioncan legally benull, it should be declared astring?. Alternatively, if nullability checking for the DTO is more nuisance than help, you can simply wrap the type in#nullable disable/#nullable restoreto turn off NRTs for this type only. - Jeroen Mostert