Nullable Reference Types and the Options Pattern

It seems, that you have two possible options here. First one is to initialize an Options properties using empty string (instead of null value) to avoid null checks

public sealed class MyOptions
{
    public string Name { get; set; } = "";
}

Second one is to make all of the properties a nullable ones and decorate them using DisallowNull precondition and NotNull postcondition.

DisallowNull means that nullable input argument should never be null, NotNull – a nullable return value will never be null.
But these attributes only affect nullable analysis for the callers of members that are annotated with them. So, you are indicating that your property can never return null or be set to null, despite nullable declaration

public sealed class MyOptions
{
    [NotNull, DisallowNull]public string? Name { get; set; }
}

and the usage example

var options = new MyOptions();
options.Name = null; //warning CS8625: Cannot convert null literal to non-nullable reference type.
options.Name = "test";

But the next example doesn’t show a warning, because nullable analysis doesn’t work properly in object initializers yet, see GitHub issue 40127 in Roslyn repository.

var options = new MyOptions { Name = null }; //no warning

(Edit: This issue was fixed already, shipped in version 16.5 in March, 2020 and should go away after updating a VS to the latest version.)

The same picture for property getter, the following sample doesn’t show any warnings, because you indicated that nullable return type can’t be null

var options = new MyOptions();
string test = options.Name.ToLower();

but attempting to set a null value and get it generates a warning (compiler is smart enough to detect such scenarios)

var options = new MyOptions() { Name = null };
string test = options.Name.ToLower(); //warning CS8602: Dereference of a possibly null reference.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)