Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should NullabilityInfo.ReadState vs. NullabilityInfo.WriteState be used when determining reference type nullability in C#?

Following the introduction of nullable reference types in C#, NullabilityInfoContext and NullabilityInfo were introduced into the System.Reflection library to allow us to see the nullability of properties, parameters, etc.

Much of the documentation and community answers give examples like this:

NullabilityInfoContext context = new();
var nullabilityInfo = context.Create(myPropertyInfo);

Console.WriteLine(nullabilityInfo.ReadState);    // Nullable
Console.WriteLine(nullabilityInfo.WriteState);   // Nullable

But this doesn't actually explain, in a real-world scenario, when one should determine nullability based on the ReadState property, or the WriteState property. Why are they even distinct? Are there any situations where WriteState would be Nullable and ReadState would be NonNullable or vice-versa?

Perhaps there is something I'm missing, but as far as I can tell, when you specify a nullable reference type with ?, it is nullable in the context of both reading and writing?

like image 539
brads3290 Avatar asked Sep 17 '25 19:09

brads3290


1 Answers

as far as I can tell, when you specify a nullable reference type with ?, it is nullable in the context of both reading and writing

Nope, here's one example. So I would not rely on one or the other. I also believe that there's a way to change whether this is evaluated for public only or not, but I'm not a fan of this feature so I don't use it (not the design, the implementation).

class Example
{
    public string? Read { get; }
    public string? Write { set => value = null; }
}

static void Main()
{
    NullabilityInfoContext context = new();
    var write = typeof(Example).GetProperty("Write");
    var read = typeof(Example).GetProperty("Read");
    var writeInfo = context.Create(write);
    var readInfo = context.Create(read);
    Console.WriteLine(writeInfo.ReadState);
    Console.WriteLine(writeInfo.WriteState);
    Console.WriteLine(readInfo.ReadState);
    Console.WriteLine(readInfo.WriteState);
}

Output:

Unknown

Nullable

Nullable

Unknown

like image 149
Zer0 Avatar answered Sep 20 '25 08:09

Zer0