Nullable reference types

Since .Net 6, reference types like string are now not nullable by default.

If you intend the value to be able to hold null then it should be explicitly declared as string?.

Any other scenario will cause the compiler to warn about potential null exceptions.

Property/field must contain a non-null value when exiting the constructor

You can assign a property the value of null! to show the compiler you know it won’t have null assigned at runtime. This is particularly suitable in DTO classes. Although, you should also consider DTOs would be better as a `record, which both takes advantage of their immutability and stops warnings for this error.

public class Address {    
    public string AddressLine1 {get; set;} = null!;
    public string? AddressLine2 {get; set;}
    public string? AddressLine3 {get; set;}
    public string City {get; set;} = null!;
    public string Postcode {get; set;} = null!;
}

public record Address(string AddressLine1, string? AddressLine2, string? AddressLine3,
        string City, string Postcode)
{    
}

If the warning relates to a field then you need to ensure it will be safely assigned.

Null-forgiving operator

If the compiler warns of a potential dereferencing error, then you can use the null-forgiving operator to tell the compiler you have ensured a variable won’t be null at runtime.

public void MyFunction(string? myString){
    if (!IsValid(myString)){
        return;
    }
    var len = myString!.length;
}

private bool IsValid(string? value){
    return !string.IsNullOrEmpty(value);
}