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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With